This works
target.sin_addr.s_addr = inet_addr("127.0.0.1");
but I want to put the IP from a website URL
I have tried
const char host[] = "http://www.google.com/";
struct hostent *host_ip;
host_ip = gethostbyaddr(host, strlen(host), 0);
I of corse did WSAStartup before I used gethostbyaddr();
I've tried this
target.sin_addr.s_addr = inet_addr(host_ip);
I've tried a few simmilar ones too but it isn't working. Could someone show me how to do this correctly.
Thank you!
EDIT:
When I do
host_ip = gethostbyaddr((char *)&host, strlen(host), 0);
std::cout << host_ip->h_addr;
It gives me
httpa104-116-116-112.deploy.static.akamaitechnologies.com
inet_addr()
accepts an IPv4 address string as input and returns the binary representation of that address. That is not what you want in this situation, since you don't have a IP address, you have a hostname instead.
You are on the right track by using gethostby...()
, but you need to use gethostbyname()
(lookup by hostname) instead of gethostbyaddr()
(lookup by IP address) 1 . And you cannot pass a full URL to either of them. gethostbyname()
takes only a hostname as input, so you need to parse the URL and extract its hostname, and then you can do something like this:
const char host[] = ...; // an IP address or a hostname, like "www.google.com" by itself
target.sin_addr.s_addr = inet_addr(host);
if (target.sin_addr.s_addr == INADDR_NONE)
{
struct hostent *phost = gethostbyname(host);
if ((phost) && (phost->h_addrtype == AF_INET))
target.sin_addr = *(in_addr*)(phost->h_addr);
...
}
else
...
1 BTW, the gethostby...
() functions are deprecated, use getaddrinfo()
and getnameinfo()
instead.
const char host[] = ...; // an IP address or a hostname, like "www.google.com" by itself
addrinfo hints = {0};
hints.ai_flags = AI_NUMERICHOST;
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
addrinfo *addr = NULL;
int ret = getaddrinfo(host, NULL, &hints, &addr);
if (ret == EAI_NONAME) // not an IP, retry as a hostname
{
hints.ai_flags = 0;
ret = getaddrinfo(host, NULL, &hints, &addr);
}
if (ret == 0)
{
target = *(sockaddr_in*)(addr->ai_addr);
freeaddrinfo(addr);
...
}
else
...
Try using getaddrinfo. There's a quick guide to using it here: http://beej.us/guide/bgnet/output/html/multipage/getaddrinfoman.html
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.