nikhil joshi
Posts tagged Networking
WinSock2 Client Server in VC++
Jul 6th
I was working with OpenSSL and VC++, I found that there are very few references available which tell us how to implement OpenSSL through VC++. But real thing missing is Working Client server in VC++ which will communicate through OpenSSL. So Writing one
Lets start with WinSock2 client server.
VC++ Code details
- VS2005
VC++ references required:
(From MSDN)Use the Winsock API by including the Winsock 2 header files. The Winsock2.h header file contains most of the Winsock functions, structures, and definitions. The Ws2tcpip.h header file contains definitions introduced in the WinSock 2 Protocol-Specific Annex document for TCP/IP that includes newer functions and structures used to retrieve IP addresses.
- Add #include <winsock2.h> and #include <ws2tcpip.h> in code
- Add build environment links to the Winsock Library file WS2_32.lib
Source code : click this link WinSock2-BasicClientServer
WinSock2 Server
We need to follow following steps to implement Server
- Initialize Winsock.
- Create and Bind the socket.
- Listen on the socket for a client.
- Accept a connection from a client.
- Receive and send data.
- Disconnect.
WinSock2 Client
- Initialize Winsock.
- Create a socket.
- Connect to the server.
- Send and receive data.
- Disconnect.
This is working fine but no fun. Lets make it working in threads.
Net will be client server communicating with each other in different threads; like read thread and write threads.
Check given IP address is valid for given machine
Mar 24th
Given code useDns.GetHostAddresses(). This function resolves machine host name to IP address. And if IP address is given it check for IP address and if valid returns given IP address.
-
string machineName = "localhost";
-
string checkIP = "127.0.0.1";
-
-
IPAddress[] ipsMachineName = null;
-
IPAddress[] ipsCheckIP = null;
-
//fetch IPs for machine
-
try {
-
ipsMachineName = Dns.GetHostAddresses(machineName);
-
}
-
catch (Exception expMachine) {
-
Console.WriteLine(string.Format("Error while retriving IP address of machine ‘{0}’ : {1} ", machineName, expMachine.Message));
-
return;
-
}
-
//Check IP addrss
-
try {
-
ipsCheckIP = Dns.GetHostAddresses(checkIP);
-
}
-
catch (Exception expIP) {
-
Console.WriteLine(string.Format("Invalid IP address: {0}", expIP.Message));
-
return;
-
}
-
//check ip address.
-
bool validIPAddress = false;
-
foreach (IPAddress machineIP in ipsMachineName) {
-
foreach (IPAddress cIP in ipsCheckIP) {
-
if (string.Compare(machineIP.ToString(), cIP.ToString(), true) == 0) {
-
validIPAddress = true;
-
break;
-
}
-
}
-
if (validIPAddress) {
-
break;
-
}
-
}
-
if (validIPAddress) {
-
Console.WriteLine("Valid IP address");
-
}
-
else {
-
Console.WriteLine("Invalid IP address");
-
}
Recent Comments