Linux下基本TCP socket编程之客户端
服务器端建立后,接下来便是客户端的编写了。客户端较之服务器较简单,下面先给出代码:
#include<stdio.h>
#include<unistd.h>
#include<string.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<netdb.h>
#define PORT 1234
#define MAXDATASIZE 100 //数据缓冲区最大长度
int main(int argc, char *argv[])
{
int sockfd, num;
//数据缓冲区
char buf[MAXDATASIZE];
struct hostent *he;
//服务器IPv4地址信息
struct sockaddr_in server;
if(argc != 2)
{
printf("Usage: %s <IP Address>\n", argv[0]);
exit(1);
}
//通过gethostbyname()得到服务端的主机信息
if((he = gethostbyname(argv[1])) == NULL)
{
printf("gethostbyname() error\n");
exit(1);
}
//使用socket()创建套接字
if((sockfd= socket(AF_INET, SOCK_STREAM, 0)) == -1)
{
printf("socket() error\n");
exit(1);
}
//初始化server地址信息
bzero(&server, sizeof(server));
server.sin_family = AF_INET;
server.sin_port = htons(PORT);
server.sin_addr = *((struct in_addr *)he->h_addr);
//使用connect()函数来配置套接字,建立一个与TCP服务器的连接
if(connect(sockfd, (struct sockaddr *)&server, sizeof(server)) == -1)
{
printf("connect() error\n");
exit(1);
}
//使用recv()函数接收服务器发送的信息
if((num = recv(sockfd, buf, MAXDATASIZE, 0)) == -1)
{
printf("recv() error\n");
exit(1);
}
buf[num - 1] = '\0';
printf("server message: %s\n", buf);
//关闭连接
close(sockfd);
return 0;
}
客户端实现的步骤如下:
(1)使用socket()函数创建套接字。
(2)调用connect()函数建立一个与TCP服务的连接。
(3)发送数据请求,接收服务器的数据应答。
(4)终止连接。
几个重要的函数:gethostbyname(),socket(),connect(),send(),recv(),close()。其中socket()、send()、recv()、close()函数已经在上一篇中介绍过,便不再重复。
下面主要介绍gethostbyname()函数与connect()函数:
#include<netdb.h>
struct hostent * gethostbyname(const char *hostname);
参数hostname是主机的域名地址。函数如果执行成功,将返回一个指向结构hostent的指针,该结构中包含了该主机的所有IPv4地址或IPv6地址;如果失败,返回空指针。
hostent结构如下:
struct hostent
{
char * h_name; /*主机的正式名称*/
char ** h_aliases; /*主机的别名列表*/
int h_addrtype; /*主机的地址类型*/
int h_length; /*主机地址长度*/
char ** h_addr_list; /*主机IP地址的列表*/
};
#define h_addr h_addr_list[0]
当客户端调用gethostbyname()函数后,便可获得指定IP对应的服务器的具体信息。当初始化server地址信息时,可通过*((struct in_addr *)he->h_addr)指定server.sin_addr。
connect()函数如下:
#include<sys/socket.h>
int connect(int sockfd, const struct sockaddr *addr, socklen_t addrlen);
TCP客户端使用connect()函数来配置套接字,建立一个与TCP服务器的连接。sockfd是由socket()函数返回的套接字描述符,addr是指向服务器的套接字地址结构的指针,addrlen是该套接字地址结构的大小。其中,sockaddr类型的结构体已在上一篇中介绍过。
客户端建立连接代码较简单,重点是掌握连接建立的过程与建立过程中调用的几个函数以及涉及到的一些数据类型。
浙公网安备 33010602011771号