一个比较实用的连接函数,支持host为域名。
#include <netdb.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>
#include <arpa/inet.h>
#include <netinet/tcp.h> #include <iostream>
using namespace std;
int my_connect(const char *host, int port)
{
char buf[1024];
struct hostent he, *p;
struct sockaddr_in sin;
socklen_t len = 0;
int sock = -1, ret = 0, err = 0, flags = 0, on = 1;
struct timeval t; assert(host != NULL); // invalid server
if (host[0] == 0 || port <= 0 || port > 65535) {
cout << "find invalid host " << host << " or port " << port << endl;
return -1;
}
//socket
if ((sock = socket(PF_INET, SOCK_STREAM, 0)) < 0) {
cout << "cannot create socket while connecting to "
<< host << ":" << port << endl;
return -1;
} //connect
bzero(&sin, sizeof(sin));
sin.sin_addr.s_addr = inet_addr(host);
if ((sin.sin_addr.s_addr) == INADDR_NONE) { /* host is not numbers-and-dots ip address */
ret = gethostbyname_r(host, &he, buf, sizeof(buf), &p, &err);
if (ret < 0 || err != 0 || p == NULL) {
cout << "cannot resolve hostname while connecting to "
<< host << ":" << port << endl;
close(sock);
return -1;
}
memcpy(&sin.sin_addr.s_addr, he.h_addr, sizeof(sin.sin_addr.s_addr));
}
sin.sin_family = AF_INET;
sin.sin_port = htons(port); flags = fcntl(sock, F_GETFL, 0);
fcntl(sock, F_SETFL, flags | O_NONBLOCK);
setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, &on, sizeof(on));
ret = connect(sock, (struct sockaddr *) &sin, sizeof(sin));
if (ret == 0) {
fcntl(sock, F_SETFL, flags);
cout << "connect to " << host << ":" << port << "OK" << endl;
return sock;
}
close(sock);
return -1;
}