Wednesday, July 17, 2013

Internet API Sockets on Linux in C

The sockets interface provides a uniform API to the lower layers of a network, and allows to implement upper layers within the sockets application.

An IPv4 address is a 32-bit data value, usually represented in "dotted quad" notion, e.g., 192.168.1.25. A port is 16-bit data value. An IP address gets a packet to a machine, a port lets the machine decide which process/service to direct it to.

Protocol TCP: Transmission Control Protocol.

Protocol IP : principal communication protocol in the internet protocol suite.

Add caption




















socket server:

#include <sys/socket.h>
#include <netinet/in.h>

char buffer[256];
int client, newsockfd, n;

/*
Initialize the socket structure:
*/
struct sockaddr_in serv_addr, cli_addr;
serv_addr.sin_family = AF_INET;                    // protocol IP
serv_addr.sin_addr.s_addr = INADDR_ANY; // run without knowing the machine address running on
serv_addr.sin_port = htons(5000);                     //  convert the port number to TCP/IP network byte 

/*
create a socket, it is also a file descriptor to read/write later.
Domain : AF_INET, for network protocol IPv4
Type      : SOCK_STREAM, for network protocol TCP
Protocol : Service provider chooses the protocol to use
*/
int listenfd = socket(AF_INET, SOCK_STREAM, 0);

/*
assign a socket to an address.
*/
bind(listenfd, (struct sockaddr*)&serv_addr, sizeof(serv_addr));

/*
prepare the socket for incoming connections, the second parameter is the most number of connection
*/
listen(listenfd, 10);

/*
accept actual connection from the client
*/
client = sizeof(cli_addr);
newsockfd = accept(listenfd,  (struct sockaddr *) &cli_addr, &client);

/*start to communicate*/
n = read(newsockfd, buffer, 255);
printf("A new message: %s\n", buffer);


socket client:

char addr_ip[] = "192.168.0.45"; // server machine address
SOCKET sock;
SOCKADDR_IN adr;

adr.sin_addr.s_addr = inet_addr(addr_ip); //convert the a string to a proper address  
adr.sin_family = AF_INET;
adr.sin_port = htons(5000); // same port number as the server

/*create the socket*/
sock = socket(AF_INET, SOCK_STREAM, 0); 

/*demand a connection*/
connect(sock, (SOCKADDR*)&adr, sizeof(adr));

/*send a message*/
unsigned char hello[] = "Hello, server!\r\n";
send(sock, (constchar *)hello, strlen(constchar *)hello);

/*close socket*/
close(socket);









No comments:

Post a Comment