小河學習日記---tcp網絡通信接收端

#include <stdio.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>

int main()
{
printf(“服務器創建socket…\n”);//創建套接字
int sockfd = socket(AF_INET,SOCK_STREAM,0);
//AF_INET:使用IPv4.SOCK_STREAM:tcp協議
if(0 > sockfd)
{
perror(“socket”);
return -1;
}
printf(“準備地址…\n”);
struct sockaddr_in addr = {};
addr.sin_family = AF_INET;
addr.sin_port = htons(7777);
//傳輸的端口號(通信兩邊的約定)
addr.sin_addr.s_addr = inet_addr(“10.0.2.15”);
//自己的私網地址/或對方的公網地址
socklen_t len = sizeof(addr);
printf(“綁定socket與地址…\n”);
if(bind(sockfd,(struct sockaddr*)&addr,len))
{
perror(“bind”);
return -1;
}
printf(“設置監聽…\n”);
if(listen(sockfd,5))
{
perror(“listen”);
return -1;
}
printf(“等待客戶端連接…\n”);
for( ; ; )
{
struct sockaddr_in addrcli = {};
int clifd = accept(sockfd,(struct sockaddr*)&addrcli,&len);
//函數接口定義的是sockaddr,而實際提供的是sockaddr_un或sockaddr_in
if(0 > clifd)
{
perror(“accept”);
continue;
}
if(0 == fork())
{
char buf[1024] = {};
for( ; ; )
{
printf(“read:”);
read(clifd,buf,sizeof(buf));
printf("%s\n",buf);
if(0 == strcmp(“quit”,buf))
{
close(clifd);
return 0;
}
printf(">");
gets(buf);
write(clifd,buf,strlen(buf)+1);
}
}
}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章