Please indicate the source: http://blog.csdn.net/gaoxiangnumber1
Welcome to my github: https://github.com/gaoxiangnumber1
- webtest工作的第四步是测试服务器状态,对应函数
void TestServerState();
。分为两步。
- 通过TcpConnect函数建立与给定服务器的Tcp连接,若成功,该函数返回创建的socket;否则返回FAIL(#define FAIL -1)。
- 根据返回值判断:如果尝试连接失败,不再进行测试,终止程序;否则,关闭本次的socket。
int TcpConnect(const char *host, int port)
函数建立与给定服务器的Tcp连接。该函数分为3步。
- 填充struct sockaddr_in:
(1). sin_family = AF_INET,代表IPv4.
(2). sin_port = htons(port).
(3). sin_addr:若host为ip地址,通过inet_addr(host)
后,即可得到网络字节序的ip地址;若host为url,那么通过gethostbyname(host)
(DNS查询)得到对应的ip地址。 - 创建套接字
socket
- 连接服务器
connect
- 填充struct sockaddr_in:
struct sockaddr_in
的定义,详见UNP-第三章。
struct in_addr
{
in_addr_t s_addr; // 32-bit IPv4 address, network byte ordered
};
struct sockaddr_in
{
uint8_t sin_len; // length of structure (16)
sa_family_t sin_family; // AF_INET
in_port_t sin_port; // 16-bit TCP or UDP port number
// network byte ordered
struct in_addr sin_addr; // 32-bit IPv4 address, network byte ordered
char sin_zero[8]; // unused
};
- TcpConnect函数源码:
// Return socket if connect to <host:post> success, -1(FAIL) on error.
int TcpConnect(const char *host, int port)
{
// Step 1. Fill struct sockaddr_in.
struct sockaddr_in sa;
bzero(&sa, sizeof(sa));
sa.sin_family = AF_INET; // IPv4
sa.sin_port = htons(port);
// Return: 32-bit binary network byte ordered IPv4 address; INADDR_NONE if error
unsigned inaddr = inet_addr(host);
if(inaddr != INADDR_NONE) // If success, i.e., if host is IP address.
{
memcpy(&sa.sin_addr, &inaddr, sizeof(inaddr));
}
else // If host is "www.example.com"
{
struct hostent *hp = gethostbyname(host);
if(hp == NULL)
{
return FAIL;
}
memcpy(&sa.sin_addr, hp->h_addr, hp->h_length);
}
// Step 2. Create socket.
int sock = socket(AF_INET, SOCK_STREAM, 0); // IPv4 & TCP
if(sock == FAIL)
{
return FAIL;
}
// Step 3. Connect to server.
if(connect(sock, (struct sockaddr *)&sa, sizeof(sa)) < 0)
{
return FAIL;
}
return sock;
}
- TestServerState完整源码
void TestServerState() // Step 4. Test whether server is working okay.
{
// Check whether the server is working by one trying connection.
int check_socket = TcpConnect(proxy_host ? proxy_host : host, proxy_port);
if(check_socket == FAIL)
{
fprintf(stderr, "Connect to server failed. Abort test.\n");
exit(SERVER_ERROR);
}
close(check_socket);
}
Please indicate the source: http://blog.csdn.net/gaoxiangnumber1
Welcome to my github: https://github.com/gaoxiangnumber1