/*
*
*/
#include <sys/types.h> /* See NOTES */
#include <sys/socket.h>
#include <string.h>
#include <unistd.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <signal.h>
/*端口号*/
#define SERVER_PORT 8888
/*mian 函数*/
int main(int argc,char **argv)
{
int isocketServer; //
int isocketclient;
socklen_t sin_size;
unsigned char ucrecvbuf[1000];
struct sockaddr_in server_addr;
struct sockaddr_in client_addr;
int iclient_nub = -1;
int recv_len;
signal(SIGCHLD,SIG_IGN);
if((isocketServer = socket(AF_INET, SOCK_STREAM, 0)) == -1)
{
printf("socket error!\n");
return -1;
}
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(SERVER_PORT);
server_addr.sin_addr.s_addr = INADDR_ANY;
memset(&(server_addr.sin_zero), 0, sizeof(server_addr.sin_zero));
/* 绑定socket到服务端地址 */
if (bind(isocketServer, (struct sockaddr *)&server_addr, sizeof(struct sockaddr)) == -1)
{
printf("Unable to bind\n");
return -1;
}
if (listen(isocketServer, 5) == -1)
{
printf("listen error\n");
return -1;
}
while(1)
{
sin_size = sizeof(struct sockaddr_in);
isocketclient=accept(isocketServer, (struct sockaddr *)&client_addr, &sin_size);
if(-1 !=isocketclient)
{
iclient_nub++;
printf("I got a connection from (%s , %d , %d)\n",inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port),iclient_nub);
if(!fork())
{
while(1)
{
recv_len=recv(isocketclient, ucrecvbuf, 999, 0);
if(recv_len<=0)
{
close(isocketclient);
return -1;
}
else
{
ucrecvbuf[recv_len+1]='\0';
printf("Get Msg form connection(%s , %d ,client_nub:%d): %s",inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port),iclient_nub,ucrecvbuf);
}
}
}
}
}
close(isocketServer);
return 0;
}