注意,该例程有个bug笔者已修正,
书中用的是server_address.sin_port = 5566;
正确应该是server_address.sin_port = htons(5566);
网络的字节顺序和主机的字节顺序是不同的,网络是大端模式,Intel x86和AMD CPU是小端模式
这么出名的《linux程序设计》书籍也有这种纰漏,实在让我对这本书的敬仰大打折扣。
server端:
#include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h>
#include <iostream>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <stdlib.h>
using namespace std;
int main()
{
int server_sockfd, client_sockfd;
unsigned int server_len, client_len;
struct sockaddr_in server_address;
struct sockaddr_in client_address;
server_sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (server_sockfd < 0)
{
perror("socket err");
exit(2);
}
server_address.sin_family = AF_INET;
server_address.sin_addr.s_addr = inet_addr("127.0.0.1");
server_address.sin_port = htons(5566);
server_len = sizeof(server_address);
if (bind(server_sockfd, reinterpret_cast<sockaddr*>(&server_address), server_len) < 0)
{
perror("bind err");
exit(3);
}
if (listen(server_sockfd, 5) < 0)
{
perror("listen err");
exit(4);
}
while (1)
{
char ch;
printf("server waiting\n");
client_len = sizeof(client_address);
client_sockfd = accept(server_sockfd, reinterpret_cast<sockaddr *>(&client_address), &client_len);
read(client_sockfd, &ch, 1);
ch++;
write(client_sockfd, &ch, 1);
close(client_sockfd);
}
return 0;
}
客户端:
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <netinet/in.h>
#include <arpa/inet.h>
int main()
{
int sockfd;
unsigned int len;
struct sockaddr_in address;
int result;
char ch = 'A';
sockfd = socket(AF_INET, SOCK_STREAM, 0);
address.sin_family = AF_INET;
address.sin_addr.s_addr = inet_addr("127.0.0.1");
address.sin_port = htons(5566);
len = sizeof(address);
result = connect(sockfd, reinterpret_cast<sockaddr *>(&address), len);
if (result == -1)
{
perror("connect server failed");
exit(1);
}
write(sockfd, &ch, 1);
read(sockfd, &ch, 1);
printf("char from server = %c\n", ch);
close(sockfd);
return 0;
}