代码拉取完成,页面将自动刷新
/*********************************************************************************
* Copyright: (C) 2018 ligang<2820724771@qq.com>
* All rights reserved.
*
* Filename: socket_server.c
* Description: This file
*
* Version: 1.0.0(03/16/2018)
* Author: ligang <2820724771@qq.com>
* ChangeLog: 1, Release initial version on "03/16/2018 10:24:16 PM"
*
********************************************************************************/
#include<stdio.h>
#include<string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include<errno.h>
#include <netinet/in.h>
#include <arpa/inet.h>
int main(int argc,char **argv)
{
int sock_fd,new_fd;
int yes=1;
struct sockaddr_in serv_addr;
char buf[1024];
sock_fd = socket(AF_INET,SOCK_STREAM,0);
if(sock_fd < 0)
{
printf("create socket is failure %s",strerror(errno));
return -1;
}
printf("create socket fd [%d]\n",sock_fd);
if (setsockopt(sock_fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1)
{
perror("setsockopt");
return -1;
}
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(8555);
serv_addr.sin_addr.s_addr = inet_addr("192.168.0.5");
memset(serv_addr.sin_zero, '\0', sizeof(serv_addr.sin_zero));
printf("begin to bind\n");
if(bind(sock_fd,(const struct sockaddr *)&serv_addr,sizeof(serv_addr))<0)
{
printf("bind is failure %s \n",strerror(errno));
return -2;
}
printf("begin to listen\n");
listen(sock_fd,13);
while(1)
{
printf("begin to accepting!\n");
new_fd = accept(sock_fd,NULL,NULL);
if(new_fd<0)
{
printf("accept is failure %s\n",strerror(errno));
return -2;
}
memset(buf,0,sizeof(buf));
printf("begin to read\n");
read(new_fd,buf,sizeof(buf));
printf("%s\n",buf);
write(new_fd,"welcome",7);
sleep(1);
close(new_fd);
}
close(sock_fd);
return 0;
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。