How to obtain the Local Public IP address in linux c

Source: Internet
Author: User

1. linux c code implementation Copy codeThe Code is 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 "};
Char res [1024];

// Initialize the 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 );
// Obtain the IP address of www.ip138.com
Ptr = gethostbyname ("www.ip138.com ");
If (NULL = ptr ){
Perror ("gethostbyname error ");
Exit (0 );
}
// Try to connect each IP address of www.ip138.com until a connection is established successfully or the connection fails. Then, 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 the packet that obtains the IP address to www.ip138.com
If (strlen (szBuffer )! = Send (sock, szBuffer, strlen (szBuffer), 0 )){
Perror ("send error ");
Exit (0 );
}

// Receive data 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 to getip. c and compile it using the following command:Copy codeThe Code is as follows: gcc-o getip. c

3. Run the programCopy codeThe Code is as follows:./getip

Related Article

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.