代码来自 http://bbs.csdn.net/topics/10348663
本地 g++ 编译时有报错,微调整
portlistener.cpp
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <unistd.h>
#define PORT 5000
#define LINK_NUM 5
int main()
{
socklen_t sock_fd;
int new_fd;
socklen_t sin_size;
struct sockaddr_in host_addr;
struct sockaddr_in client_addr;
if((sock_fd = socket(AF_INET,SOCK_STREAM,0)) == -1)
{
perror("socket");
exit(1);
}
host_addr.sin_family = AF_INET;
host_addr.sin_port = htons(PORT);
host_addr.sin_addr.s_addr = INADDR_ANY;
bzero(&(host_addr.sin_zero),8);
if(bind(sock_fd,(struct sockaddr*)&host_addr,sizeof(struct sockaddr)) == -1)
{
perror("bind");
exit(1);
}
if(listen(sock_fd,LINK_NUM) == -1)
{
perror("listen");
exit(1);
}
while(1)
{
sin_size = sizeof(struct sockaddr_in);
if((new_fd = accept(sock_fd,(struct sockaddr*)&client_addr,&sin_size)) == -1)
{
perror("accept");
continue;
}
printf("server:got connection from %s\n",inet_ntoa(client_addr.sin_addr));
if(!fork())
{
if(send(new_fd,"hi, man !\n",10,0) == -1)
{
perror("send");
close(new_fd);
exit(0);
}
close(new_fd);
}
}
while(waitpid(-1,NULL,WNOHANG)>0);
return 0;
}