#include <stdio.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#define IPADDRESS "0.0.0.0"
#define PORT 8787
#define LISTENQ 5
#define MAXLINE 1024
int main() {
// int socket (int domain, int type, int protocol)
int listenfd = socket(AF_INET, SOCK_STREAM, 0);
if(listenfd == -1){
printf("socket error");
return -1;
}
// int bind (int fd, sockaddr * addr, socklen_t len)
struct sockaddr_in servaddr;
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(PORT);
// servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
inet_pton(AF_INET, IPADDRESS, &servaddr.sin_addr);
if (bind(listenfd, (struct sockaddr*)&servaddr, sizeof(servaddr)) == -1) {
printf("bind error");
return -1;
}
// int listen (int socketfd, int backlog)
if (listen(listenfd,LISTENQ) == -1) {
printf("listen error");
return -1;
}
// int accept(int listensockfd, struct sockaddr *cliaddr, socklen_t *addrlen)
struct sockaddr_in cliaddr;
socklen_t cliaddrlen = sizeof(cliaddr);
int connfd;
if ((connfd = accept(listenfd, (struct sockaddr*)&cliaddr, &cliaddrlen)) == -1) {
perror("accept error:");
return 1;
}else{
printf("start up: sleep 3s");
sleep(3);
}
printf("accept a new client: %s:%d\n", inet_ntoa(cliaddr.sin_addr), cliaddr.sin_port);
// ssize_t read (int socketfd, void *buffer, size_t size)
// ssize_t write (int socketfd, const void *buffer, size_t size)
int n;
char buf[MAXLINE];
for (; ;) {
n = read(connfd,buf,MAXLINE);
if (n==0) {
break;
}
// printf("read msg is: ");
// write(STDOUT_FILENO,buf,n);
//向客户端发送buf
write(connfd,buf,n);
}
close(connfd);
close(listenfd);
}
- 若没加入 <arpa/inet.h>, 执行 printf("accept a new client: %s:%d\n", inet_ntoa(cliaddr.sin_addr), cliaddr.sin_port); 这行语句时,会报Segmentation fault (core dumped)的错误