2 Star 1 Fork 0

李刚/socket

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
my_socket_server.c 2.06 KB
一键复制 编辑 原始数据 按行查看 历史
李刚 提交于 2018-03-21 18:44 . polish file my_socket_server.c
/*********************************************************************************
* 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;
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
C
1
https://gitee.com/ZuoKanYunQi/socket.git
git@gitee.com:ZuoKanYunQi/socket.git
ZuoKanYunQi
socket
socket
master

搜索帮助

0d507c66 1850385 C8b1a773 1850385