Solved

Finding Ip address using sockets

Posted on 1998-01-12
1
193 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

Introduction This article is the first in a series of articles about the C/C++ Visual Studio Express debugger.  It provides a quick start guide in using the debugger. Part 2 focuses on additional topics in breakpoints.  Lastly, Part 3 focuses on th…
Introduction This article is a continuation of the C/C++ Visual Studio Express debugger series. Part 1 provided a quick start guide in using the debugger. Part 2 focused on additional topics in breakpoints. As your assignments become a little more …
The viewer will learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.
The viewer will be introduced to the member functions push_back and pop_back of the vector class. The video will teach the difference between the two as well as how to use each one along with its functionality.

763 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