设为首页 加入收藏

TOP

网络编程client和server(二)
2014-11-24 00:36:40 来源: 作者: 【 】 浏览:86
Tags:网络编程 client server
es;
int status;
int sockfd;

int connFd;
struct sockaddr_in cliAddr;

int sendSta;
char *msg;

if (argc != 2) {
fprintf(stderr, "Usage: Not found Read File");
return 1;
}

memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_PASSIVE;

status = getaddrinfo(NULL, SERVPORT, &hints, &res);

if (status != 0) {
fprintf(stderr, "getaddrinfo, fail!");
return 2;
}

sockfd = socket(res->ai_family, res->ai_socktype, res->ai_protocol);

bind(sockfd, res->ai_addr, res->ai_addrlen);

listen(sockfd, 5);

printf("======== Please Wait Client =========\n");

while(1) { // loop forever!
char ipstr[INET_ADDRSTRLEN];
void *addr;

int len = sizeof(cliAddr);
connFd = accept(sockfd, (struct sockaddr *)&cliAddr, &len);

/* View Client IP */
struct sockaddr_in *ipv4 = (struct sockaddr_in *)&cliAddr;
addr = &(ipv4->sin_addr);

inet_ntop(AF_INET, addr, ipstr, sizeof(ipstr));
printf("client: %s\n", ipstr);

/* Copy Data */
msg = "Hello world!";
sendSta = send(connFd, msg, strlen(msg), 0);

close(connFd);
}

close(sockfd);
return 0;
}

摘自 xiaobin_HLJ80的专栏

首页 上一页 1 2 下一页 尾页 2/2/2
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇错误解决:no newline at end of .. 下一篇图像(层)正常混合模式详解(上)

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: