Solved

Finding Ip address using sockets

Posted on 1998-01-12
1
192 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 20 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

Free Tool: Postgres Monitoring System

A PHP and Perl based system to collect and display usage statistics from PostgreSQL databases.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

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. …
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
The viewer will learn how to use the return statement in functions in C++. The video will also teach the user how to pass data to a function and have the function return data back for further processing.
The viewer will learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.

839 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