Linux C Get the realization method of native public network IP _c language

Source: Internet
Author: User
Tags get ip strlen
1, Linux C code implementation
Copy Code code as follows:

#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/socket.h>
typedef enum {False,true}bool;
int main ()
{
BOOL Flag;
int sock;
char **pptr = NULL;
struct sockaddr_in destaddr;
struct Hostent *ptr = NULL;
Char destip[128];
Char szbuffer[] = {"Get/ip2city.asp http/1.1\r\nhost:www.ip138.com\r\nconnection:close\r\n\r\n"};
Char res[1024];

Initialize socket
Sock = socket (af_inet,sock_stream,0);
if (-1 = sock) {
Perror ("creat socket failed");
Exit (0);
}

Bzero ((void *) &destaddr,sizeof (DESTADDR));
destaddr.sin_family = af_inet;
Destaddr.sin_port = htons (80);
The first is to get the IP address of the www.ip138.com
ptr = gethostbyname ("www.ip138.com");
if (NULL = = ptr) {
Perror ("gethostbyname error");
Exit (0);
}
To try the connection for each IP of the www.ip138.com until one of the connections is successful or cannot connect, exit the program
for (flag=false,pptr=ptr->h_addr_list; NULL!= *pptr; ++PPTR) {
Inet_ntop (ptr->h_addrtype,*pptr,destip,sizeof (Destip));
printf ("addr:%s\n", Destip);
DESTADDR.SIN_ADDR.S_ADDR = inet_addr (Destip);
if ( -1!=connect (sock, struct sockaddr *) &destaddr,sizeof (struct sockaddr))) {
Flag = true;
Break
}
}

if (false = = flag) {
Perror ("Connect failed");
}

Send a packet to get IP to www.ip138.com
if (strlen (szbuffer)!= Send (Sock,szbuffer,strlen (szbuffer), 0)) {
Perror ("Send Error");
Exit (0);
}

Receive Packets
if ( -1 = = recv (sock,res,1024,0)) {
Perror ("recv error");
Exit (0);
}

printf ("res:\n%s\n", res);
return 0;
}

2, save the above code GETIP.C, and use the following command to compile
Copy Code code as follows:

Gcc-o GetIP getip.c

3. Run the program
Copy Code code as follows:

./getip

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.