日期:2014-05-16 浏览次数:20857 次
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#define LISTENQ 5
#define MAX_BUFFER_SIZE 512
#define HOST_ADDR "192.168.56.102"
int listenfd;
unsigned char buf[MAX_BUFFER_SIZE];
int InitSocket() {
struct sockaddr_in server_addr;
listenfd = socket(AF_INET, SOCK_STREAM, 0);
if (listenfd < 0) {
perror("Socket created failed:");
return -1;
}
{
int opt = 1;
setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
}
// bzero(&server_addr, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(6666);
// server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
// TODO: cann't designate IP
//unsigned char addr[] = HOST_ADDR;
//inet_ntoa(addr , &server_addr.sin_addr);
if (inet_ntoa(HOST_ADDR, &server_addr.sin_addr) == 0) { //XXX:
perror("inet_ntoa error:");
return -1;
}
if (bind(listenfd, (struct sockaddr*)&server_addr,
sizeof(server_addr)) < 0) {
perror("Bind error:");
return -1;
}
if (listen(listenfd, LISTENQ) < 0) {
perror("Listening error:");
return -1;
}
printf("Listening ...\n");
}
int Reading() {
struct sockaddr_in client_addr;
socklen_t len = sizeof(client_addr);
int connfd = accept(listenfd, (struct sockaddr *)&client_addr, &len);
if (connfd < 0) {
perror("accept error:");
return -1;
}
printf("Connect from %s , port %d \n",
inet_ntoa(client_addr.sin_addr.s_addr),
ntohs(client_addr.sin_port));
int recv_len = read(connfd, buf, MAX_BUFFER_SIZE);
int i;
printf("recv_len = %d\n", recv_len);
for (i = 0; i < recv_len; ++i)