?? 1.c
字號(hào):
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/wait.h>
#define MYPORT 3490 /*服務(wù)器監(jiān)聽(tīng)端口號(hào) */
#define BACKLOG 10 /* 最大同時(shí)連接請(qǐng)求數(shù) */
main()
{
intsock fd,new_fd; /* 監(jiān)聽(tīng)socket: sock_fd,數(shù)據(jù)傳輸socket:new_fd*/
struct sockaddr_in my_addr; /* 本機(jī)地址信息 */
struct sockaddr_in their_addr; /* 客戶(hù)地址信息 */
int sin_size;
if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) { /*錯(cuò)誤檢測(cè) */
perror("socket");
exit(1);
}
my_addr.sin_family=AF_INET;
my_addr.sin_port=htons(MYPORT);
my_addr.sin_addr.s_addr = INADDR_ANY;
bzero(&(my_addr.sin_zero),8);
if (bind(sockfd, (struct sockaddr *)&my_addr, sizeof(struct sockaddr)) == -1) {/*錯(cuò)誤檢測(cè)*/
perror("bind");
exit(1);
}
if (listen(sockfd, BACKLOG) == -1) {/*錯(cuò)誤檢測(cè)*/
perror("listen");
exit(1);
}
while(1) { /* main accept() loop */
sin_size = sizeof(struct sockaddr_in);
if ((new_fd = accept(sockfd, (struct sockaddr *)&their_addr, &sin_size)) == -1) {
perror("accept");
continue;
}
printf("server: got connection from %s",inet_ntoa(their_addr.sin_addr));
if (!fork()) { /* 子進(jìn)程代碼段 */
if (send(new_fd, "Hello, world!", 14, 0) == -1)
perror("send");
close(new_fd);
exit(0);
}
close(new_fd); /* 父進(jìn)程不再需要該socket */
waitpid(-1,NULL,WNOHANG) > 0 /*等待子進(jìn)程結(jié)束,清除子進(jìn)程所占用資源*/
}
}
?? 快捷鍵說(shuō)明
復(fù)制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號(hào)
Ctrl + =
減小字號(hào)
Ctrl + -