Solved

Finding Ip address using sockets

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

Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

Join & Write a Comment

Written by John Humphreys C++ Threading and the POSIX Library This article will cover the basic information that you need to know in order to make use of the POSIX threading library available for C and C++ on UNIX and most Linux systems.   [s…
Many modern programming languages support the concept of a property -- a class member that combines characteristics of both a data member and a method.  These are sometimes called "smart fields" because you can add logic that is applied automaticall…
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++.

747 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

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now