int main(void)
{
struct sockaddr_in sin;
struct sockaddr_in pin;
int sock_descriptor;
int temp_sock_descriptor;
int address_size;
char buf[16384];
int i, len;
printf("Now we starting recived the data ............................................\n");
printf("Recived from client: %s\n", buf);
//for this server example,we just convert the characters to upper case:
len = strlen(buf);
for(i = 0; i < len; i++)
buf = toupper(buf); //convert to input to capital
printf("Chevered recive data from client:%s\n", buf);
完成上面的工作后,在命令行输入make回车即可进行编译,期间可能有些警告信息,不要理他。
你可以打开两个终端,以便于测试。先运行服务器程序等待客户端连接。然后再运行客户端程序。
运行结果如下:
服务器端结果
[hyj@localhost tcpip]$ ./server
Accepting connections ...
Now we starting recived the data ............................................
Recived from client: This is a test.
Chevered recive data from client:THIS IS A TEST.
使用ctrl+C可以终止。
客户端结果
[hyj@localhost tcpip]$ ./client "This is a test."
Get host info is ok!
Sending message is :
This is a test. to server...
...sent message... wait for response...
Response from server:
THIS IS A TEST.
其中可能出现的错误有一下几点:
1.使用了已经被占用的端口;
2.指针错误的使用,尤其是在接收和发送这两个函数上;
3.套界字初始化有问题;
下面介绍其中的几个结构:
1.struct sockaddr{
unsigned short sa_family;//address family,FA_xxx
char sa_data[14];//14bytes of protocol address
}这个结构一般已经不再使用,常用sockaddr_in代替;
2.struct sockaddr_in{
short int sin_family;
unsigned short int sin_port;
struct in_addr sin_addr;
unsigned char sin_zero[8];//填充0以保持与sockaddr同样的大小
}
3.struct hostent{
char *h_name; //主机的正式名称
char **h_aliases; //别名列表
int h_addrtype;//主机地址类型:AF_xxx
int H_length;//主机地址长度:4字节
char **h_addr_list;//主机IP地址列表
}