Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

Finding Ip address using sockets

Posted on 1998-01-12
1
Medium Priority
?
197 Views
Last Modified: 2010-04-10
I need to find a way to know my own IP and to find the IP of another computer that is attached to another app through a socket connection.  I am using MFC and VC++ 5.0.  I have used sockets in many ways, but have never been able to find out the local machines IP with C++.
Thanks
Georg
0
Comment
Question by:georgh
1 Comment
 
LVL 32

Accepted Solution

by:
jhance earned 80 total points
ID: 1178205
Use the gethostbyname() WINSOCK function.  This will return the IP address of the specified host. To get your IP, just put in the hostname for your workstation.

Here is an example program:

#include <stdio.h>
#include <winsock.h>

void main()
{
// First, initialize the WINSOCK interface
WORD wVersionRequested;
WSADATA wsaData;
int err;
HOSTENT *hostent;
IN_ADDR in_addr;

wVersionRequested = MAKEWORD( 2, 0 );
err = WSAStartup( wVersionRequested, &wsaData );
if ( err != 0 ) {
/* Tell the user that we could not find a usable */
/* WinSock DLL. */
printf("ERROR: Failed to initialize WINSOCK");
return;
}


// Do a DNS lookup of an IP from it's hostname
hostent = gethostbyname("www.yahoo.com");
if(hostent != NULL){
memcpy(&in_addr, hostent->h_addr_list[0], 4);
printf("www.yahoo.com = %s\n", inet_ntoa(in_addr));
}
else{
printf("Error, lookup failed\n");
}
}  
 

0

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

When writing generic code, using template meta-programming techniques, it is sometimes useful to know if a type is convertible to another type. A good example of when this might be is if you are writing diagnostic instrumentation for code to generat…
What is C++ STL?: STL stands for Standard Template Library and is a part of standard C++ libraries. It contains many useful data structures (containers) and algorithms, which can spare you a lot of the time. Today we will look at the STL Vector. …
The viewer will learn how to user default arguments when defining functions. This method of defining functions will be contrasted with the non-default-argument of defining functions.
The viewer will learn how to clear a vector as well as how to detect empty vectors in C++.
Suggested Courses
Course of the Month13 days, 3 hours left to enroll

972 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question