server socket AF_INET

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <iostream>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
int main() {
int server_sockfd, client_sockfd;
sockaddr_in server_address;
sockaddr_in client_address;
server_sockfd = socket(AF_INET, SOCK_STREAM, 0);
server_address.sin_family = AF_INET;
server_address.sin_addr.s_addr = inet_addr("127.0.0.1");
server_address.sin_port = htons(9734);
int server_len = sizeof(server_address);
int bind_return = bind(server_sockfd, (sockaddr*)&server_address, server_len);
if (-1 == bind_return) {
std::cout<<"error bind"<<std::endl;
return 0;
}
listen(server_sockfd, 5);
int client_len;
char ch = 'A';
while(1) {
std::cout<<"server is wating...";
client_sockfd = accept(server_sockfd, (sockaddr*)&client_address, (socklen_t*)&client_len);
read(client_sockfd, &ch, 1);
ch++;
write(client_sockfd, &ch, 1);
close(client_sockfd);
}
return 0;
}