/* **************************
* Process IPC by Stream Socket
* the code of server
* *************************/
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <netdb.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#define BUF_SIZE 128
int main()
{
int server_fd,client_fd;
int index = 0;
int res;
char buf[BUF_SIZE];
char * host = "localhost"; //using localhost IP address:127.0.0.1
char * server = "1080"; //using port 1080, it must be more then 1024
struct addrinfo hints;
struct addrinfo *result;
//init the value
memset(&hints,0,sizeof(struct addrinfo));
result = NULL;
//set the rule for sockey address
//hints.ai_flags = AI_ADDRCONFIG | AI_CANONNAME;
hints.ai_flags = AI_NUMERICSERV;
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
//get address info ,it has all attribute of socket
res = getaddrinfo(host,server,&hints,&result);
if(0 != res)
{
printf("get address infomation failed .Error code:%d \n",res);
return 1;
}
//create socket
server_fd = socket(result->ai_family,result->ai_socktype,result->ai_protocol);
if(-1 == client_fd)
{
printf("create socket failed \n");
return 1;
}
//bind address to socket
res = bind(server_fd,result->ai_addr,result->ai_addrlen);
if(-1 == res)
{
printf("bind address failed \n");
return 1;
}
//create queue of socket and listen for it
res = listen(server_fd,2);
if(-1 == res)
{
printf("create queue fo socket failed \n");
return 1;
}
while(index++ < 2)
{
client_fd = accept(server_fd,NULL,NULL);
if(-1 == client_fd)
{
printf("can't accept request of client \n");
return 1;
}
// read data by socket
res = read(client_fd,buf,BUF_SIZE);
if(-1 == res)
{
printf("read data by socket failed \n");
return 1;
}
printf("[server] receiving data (%s) from client by socket\n",buf);
// close socket
res = close(client_fd);
if(-1 == res)
{
printf("close socket failed \n");
return 1;
}
}
if(result->ai_next)
freeaddrinfo(result);
// close socket
res = close(server_fd);
if(-1 == res)
{
printf("close socket failed \n");
return 1;
}
return 0;
}