日期:2014-05-16 浏览次数:20780 次
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <fcntl.h>
#define LISTEN_IP "0.0.0.0"
#define LISTEN_PORT 818
#define MAX_SOCKFD 10
#define BUFFER_SIZE 256
int main(int argc, char *argv[]) {
int sockfd;
struct sockaddr_in server_addr;
int is_connected[MAX_SOCKFD] = {0,};
fd_set readfds;
int fd;
int newfd;
struct sockaddr_in client_addr;
socklen_t addr_len;
char buffer[BUFFER_SIZE];
int optval = 1;
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if(sockfd < 0) {
printf("[%d] %s\n", errno, strerror(errno));
return 1;
}
if(!setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval)) < 1) {
printf("[%d] %s\n", errno, strerror(errno));
return 1;
}
bzero(&server_addr, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(LISTEN_PORT);
inet_aton(LISTEN_IP, &server_addr.sin_addr);
//server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
if(bind(sockfd, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0) {
printf("[%d] %s\n", errno, strerror(errno));
return 1;
}
if(listen(sockfd, 20) < 0) {
printf("[%d] %s\n", errno, strerror(errno));
return 1;
}
printf("[%d] listen at %s:%d\n", sockfd, LISTEN_IP, LISTEN_PORT);
while(1) {
FD_ZERO(&readfds);
FD_SET(sockfd, &readfds);
for(fd = 0; fd < MAX_SOCKFD; fd++) {
if(is_connected[fd]) FD_SET(fd, &readfds);
}
if(select(MAX_SOCKFD, &readfds, NULL, NULL, NULL) < 0) {
&n