Monday, December 10, 2007

TCP Server and Client application

TCPServer :
-----------
struct sockaddr_in local, from;

WSADATA wsaData;

SOCKET listen_socket, msgsock;

if ((retval = WSAStartup(0x202, &wsaData)) != 0) {//Error}


local.sin_family = AF_INET;

local.sin_addr.s_addr = (!ip_address) ? INADDR_ANY:inet_addr(ip_address);

local.sin_port = htons(port);

listen_socket = socket(AF_INET, SOCK_STREAM,0);

if (bind(listen_socket, (struct sockaddr*)&local, sizeof(local)) == SOCKET_ERROR) { //Error Return}

//we can't use a UDP socket
if (listen(listen_socket,5) == SOCKET_ERROR) {//Error Return}

msgsock = accept(listen_socket, (struct sockaddr*)&from, &fromlen);

retval = recv(msgsock, Buffer, sizeof(Buffer), 0);

retval = send(msgsock, Buffer, sizeof(Buffer), 0);



TCP client :
-------------
struct sockaddr_in server;

struct hostent *hp;

WSADATA wsaData;

SOCKET conn_socket;

if ((retval = WSAStartup(0x202, &wsaData)) != 0) {//Error}

if (isalpha(server_name[0]))

{ // server address is a name

hp = gethostbyname(server_name);

}

else

{ // Convert nnn.nnn address to a usable one

addr = inet_addr(server_name);

hp = gethostbyaddr((char *)&addr, 4, AF_INET);

}

if(hp == NULL) { //Error return }

memset(&server, 0, sizeof(server));

memcpy(&(server.sin_addr), hp->h_addr, hp->h_length);

server.sin_family = hp->h_addrtype;

server.sin_port = htons(port);

conn_socket = socket(AF_INET, SOCK_STREAM, 0); /* Open a socket */

if (connect(conn_socket, (struct sockaddr*)&server, sizeof(server)) == SOCKET_ERROR) {//Error Return}

retval = send(conn_socket, Buffer, sizeof(Buffer), 0);
retval = recv(conn_socket, Buffer, sizeof(Buffer), 0);


closesocket(conn_socket);

WSACleanup();

Labels: , , ,

0 Comments:

Post a Comment

<< Home