To get IP Address from interface name in Windows - c++

I like to know, winapi from which i can get ipaddress using interface name. The Linux version of which is as below.
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <netinet/in.h>
#include <net/if.h>
#include <unistd.h>
#include <arpa/inet.h>
int main()
{
int fd;
struct ifreq ifr;
char iface[] = "eth0";
fd = socket(AF_INET, SOCK_DGRAM, 0);
//Type of address to retrieve - IPv4 IP address
ifr.ifr_addr.sa_family = AF_INET;
//Copy the interface name in the ifreq structure
strncpy(ifr.ifr_name , iface , IFNAMSIZ-1);
ioctl(fd, SIOCGIFADDR, &ifr);
close(fd);
//display result
printf("%s - %s\n" , iface , inet_ntoa(( (struct sockaddr_in *)&ifr.ifr_addr )->sin_addr) );
return 0;
}
I am looking similar functionality ( as code above) but for windows in C++.

may be you can tweak it to your needs...
http://kodeyard.blogspot.in/2009/09/get-ip-address-in-cwindows.html

See sample of GetAdaptersAddresses function. FriendlyName and FirstUnicastAddress are fields you need.
http://msdn.microsoft.com/en-us/library/windows/desktop/aa365915%28v=vs.85%29.aspx
See also: Get network interface name from IPv4 address

SIGAR is a cross-platform library for getting system info (CPU, RAM, DISK, and Network). It will allow you to list all network interfaces on Mac / Windows / Linux and get any other info you may need.
http://support.hyperic.com/display/SIGAR/Home
If you don't want to use the whole library, I am sure you could inspect the code to find just the piece you need.

You have to initialize WinSock first, and only then use gethostname, gethostbyname and inet_ntoa functions. The following link will help you.

Related

cpp connect() function is blocked indefinitely

#include <sys/socket.h>
#include <cstdio>
#include <stdlib.h>
#include <iostream>
#include <errno.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <netdb.h>
#include <unistd.h>
#define BUFSIZE 5000
#define PORT 80
using namespace std;
int main(int argc, char* argv[]){
char buffer[BUFSIZE];
int sockfd;
struct sockaddr_in their_addr;
if((sockfd = socket(PF_INET, SOCK_STREAM, 0)) == -1){
perror("Socket generating failed");
exit(1);
}
their_addr.sin_family = AF_INET;
their_addr.sin_port = htons(PORT);
their_addr.sin_addr.s_addr = htonl(((struct in_addr*)gethostbyname("www.google.com")->h_addr_list[0])->s_addr);
if(connect(sockfd, (struct sockaddr*)&their_addr, sizeof(struct sockaddr)) == -1){ // stops at here!
perror("Connection failed");
exit(1);
}
close(sockfd);
return 0;
As a test of a combination of gethostbyname + connect, I wrote a simple code.
It queries the IP address of google by means of gethostbyname(), connects to google do nothing, and close the socket.
However, the program just stops at a line of the connect() function without any error including perror().
How can I fix this?
Get the s_addr, make sure it is an ipv4 address, and then on the command line try to ping that address with the command 'ping addr'
After that you could try a program like nmap but most likely ping will be enough.
There is probably nothing wrong with your code. You need to see if there is a proxy or firewall or anything else interfering with your network connection. You will also want to confirm you are getting an ipv4 address with gethostbyname
I solved this problem by removing htonl. I don't know why, and what could happen in future as a result of removing it. But this would be my best.
The socket API is not part of C++, it is posix. gethostbyname()is obsolete, use getaddrinfo instead. Read the appropriate man page, it also contains as example precisely the code you look for...

Setting IP address in Linux using c++

I want to set my IP, subnet, DHCP addresses but I need to do it by using c++. I have researched on the internet and tried some code. Unfortunately, it didn't work. And one more thing it supposes to be secure to run it, I mean I cannot use functions that need privilege like system() and so on. Is there any advice you can give me?
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <netinet/in.h>
#include <net/if.h>
#include <arpa/inet.h>
int main()
{
char ip_address[15];
int fd;
struct ifreq ifr;
struct sockaddr_in *addr;
/*Read IP Address*/
printf("Enter Ip Address: ");
scanf("%s",ip_address);
/*AF_INET - to define network interface IPv4*/
/*Creating soket for it.*/
fd = socket(AF_INET, SOCK_DGRAM, 0);
/*AF_INET - to define IPv4 Address type.*/
ifr.ifr_addr.sa_family = AF_INET;
/*eth0 - define the ifr_name - port name
where network attached.*/
memcpy(ifr.ifr_name, "eth0", IFNAMSIZ-1);
/*defining the sockaddr_in*/
addr=(struct sockaddr_in *)&ifr.ifr_addr;
/*convert ip address in correct format to write*/
inet_pton(AF_INET,ip_address,&addr->sin_addr);
/*Setting the Ip Address using ioctl*/
ioctl(fd, SIOCSIFADDR, &ifr);
/*closing fd*/
close(fd);
printf("IP Address updated sucessfully.\n");
/*Getting the Ip Address after Updating.*/
/*clear ip_address buffer with 0x20- space*/
memset((unsigned char*)ip_address,0x20,15);
ioctl(fd, SIOCGIFADDR, &ifr);
/*Extracting Ip Address*/
strcpy(ip_address,inet_ntoa(((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr));
printf("Updated IP Address is: %s\n",ip_address);
return 0;
}
This code is what I have tried so far. After I run this I check ifconfig but nothing is changed.

Raspbian C++ Error: expected primary expression before 'struct'

I am trying to write a program for my raspberry pi that changes its system time to the time from a GPS unit on the same network. The GPS sends out a 72 byte UDP packet across port 3000. I am new to socket programming so I am unsure where I am going wrong.
The trouble that I am having is that I can't seem to get it to build with g++. I am getting the following error:
So the main error seems to be in the line
char A = struct sockaddr_in address;
Here is the start of my program and the method where I create the socket and where the error is located, if you would like the main method of my program then I will add it too.
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <time.h>
#include <sys/time.h>
#include <errno.h>
#include <math.h>
// defines the socket used by the GPS
#define PORT 3000
/****************************/
int CreateSocket(int port)
/****************************/
{
// Create an UDP-socket
int sock = socket(AF_INET, SOCK_DGRAM, 0);
// Check if UDP-socket was created
if(sock==-1)
{
fprintf(stderr, "1CreateSocket: socket failed\n");
return -1;
}
// Bind it to the local IP-address
struct sockaddr_in address;
char A = struct sockaddr_in address;
fprintf(stderr, A);
// Pointer to the block of memory to fill with address data
memset(&address, 0, sizeof(address));
address.sin_family = AF_INET; // Address family for IP-address
address.sin_addr.s_addr = htonl(INADDR_ANY); // converts the unsigned integer hostlong from host byte order to network byte order
address.sin_port = htons(port); // converts the unsigned short integer hostshort from host byte order to network byte order
// Check if IP-address is correct, if not Socket failed. Otherwise it returns the socket
if(bind(sock, (struct sockaddr *) &address, sizeof(address))==-1)
{
fprintf(stderr, "2CreateSocket: bind failed\n");
close(sock);
return -1;
}
return sock;
}
Can anyone see any obvious errors here? Thanks
You don't really need these two lines:
char A = struct sockaddr_in address;
fprintf(stderr, A);
You can delete them, since they don't do anything useful, and they have a syntax error.
And to do some extra cleanup, the comment of the binding above those lines that can be deleted should actually go above the call to bind().

recvfrom works with INADDR_ANY, but specifying certain interface doesn't work

I wrote a program that join source specific multicast group and receive udp multicast packets:
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <netdb.h>
#include <unistd.h>
#include <net/if.h>
typedef unsigned int UINT32;
int join_ssm_group(int s, UINT32 group, UINT32 source, UINT32 inter) {
struct ip_mreq_source imr;
imr.imr_multiaddr.s_addr = group;
imr.imr_sourceaddr.s_addr = source;
imr.imr_interface.s_addr = inter;
return setsockopt(s, IPPROTO_IP, IP_ADD_SOURCE_MEMBERSHIP, (char *) &imr, sizeof(imr));
}
UINT32 LISTEN_INTERFACE = inet_addr("10.10.1.2");
int main(int argc, char *argv[]) {
if (argc<3) {
printf(" Use: %s <group> <source> <port>", argv[0]);
return 1;
}
// Make socket
int sd = socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP);
struct sockaddr_in Sender;
socklen_t SenderAddrSize = sizeof( Sender );
struct sockaddr_in binda;
// Bind it to listen appropriate UDP port
binda.sin_family = AF_INET;
binda.sin_port = htons( atoi(argv[3]));
= INADDR_ANY;
// binda.sin_addr.s_addr = LISTEN_INTERFACE;
bind(sd,(struct sockaddr*)&binda, sizeof(binda));
// Join to group
join_ssm_group( sd, inet_addr(argv[1]),
inet_addr(argv[2]),
INADDR_ANY );
char buf[65536];
UINT32 seq;
while(1) {
printf("try receive\n");
int res=recvfrom(sd,(char*)buf,sizeof(buf),0, (struct sockaddr *)& Sender, &SenderAddrSize);
printf("received\n");
seq = *(UINT32*)buf;
printf("scr=:%12s;\tseq=%6d;\tlen=%4d\n", inet_ntoa(Sender.sin_addr), seq, res);
}
return 0;
}
It works fine but note that I'm using binda.sin_addr.s_addr = INADDR_ANY;. netstat shows this:
netstat -a | grep 16002
udp 0 0 0.0.0.0:16002 0.0.0.0:*
When I change it to binda.sin_addr.s_addr = LISTEN_INTERFACE; program stops working - it can not recieve packets, it hangs in recvfrom. netstat shows this:
netstat -a | grep 16002
udp 0 0 localhost.localdo:16002 0.0.0.0:*
In both cases tcpdump shows that data is online, so the problem is that I can not receive data on the specific interface, only on ALL interfaces. I'm using RHEL 7, teaming, and LISTEN_INTERFACE is the IP of the corresponding VLAN. Why my code doesn't work and how to troubleshoot it? I do not want to use INADDR_ANY for performance reasons - listening ALL interfaces would be more expensive than listeining certain interface.
upd passing LISTEN_INTERFACE to both join_ssm_group and and binda.sin_addr.s_addr doesn't work too. BTW similar Windows version of such code works on the same PC under Windows Server 2008 R2, but it doesn't work in RHEL 7. I guess I should check these:
if RHEL 7 receives data on the requreid interface on the required port (answer is Yes, proved by tcpdump)
if socket is listening on the required interface on the required port (answer is Yes, proved by netstat?)
if both answers above are Yes then how is it possible that call to recvfrom doesn't receive data?
Well probably this question more about RHEL 7 now, than about c++.
When you join the multicast group you need to specify the same interface that you are listening on, or join it via all interfaces in a loop.
However listening on all interfaces is the norm. It is not 'slow', and it is a 'good idea', unless you have a specific reason to restrict who can connect.

how to scan wireless network and display the list of all computers and devices connected

I need to build a tool (c++) very much like "Wireless Network Watcher" which is a small utility that scans your wireless network and displays the list of all computers and devices that are currently connected to your network.
here's the existing tool http://www.nirsoft.net/utils/wireless_network_watcher.html
I need to know what are the win32 sdk functions to use to build this kind of functionality: scan the wireless network I am connected to and display all computers and devices connected to it.
ok, it seems is done this way: first sent an ARP request packet to each possible IP address in the network (you calculate them based on the net mask and the interface ip), for this step you can use SendARP functions. Then you have to call getnameinfo for each IP that responded previously, or you can send an NetBios request packet (port 137) to retreive the name of the device, if it has one, or know how to respond to that request.
for some networks this can take awhile (very long time).
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <netinet/ip_icmp.h>
#include <time.h>
#include <fcntl.h>
#include <signal.h>
#include <time.h>
// Define the Packet Constants
// ping packet size
#define PING_PKT_S 64
// Automatic port number
#define PORT_NO 0
// Automatic port number
#define PING_SLEEP_RATE 1000000
// Gives the timeout delay for receiving packets
// in seconds
#define RECV_TIMEOUT 1
// Performs a DNS lookup
char* dns_lookup(char* addr_host, struct sockaddr_in* addr_con) {
// printf("\nResolving DNS..\n");
struct hostent* host_entity;
char* ip = (char*)malloc(NI_MAXHOST * sizeof(char));
int i;
if ((host_entity = gethostbyname(addr_host)) == NULL) {
// No ip found for hostname
return NULL;
}
// filling up address structure
strcpy(ip, inet_ntoa(*(struct in_addr*)host_entity->h_addr));
(*addr_con).sin_family = host_entity->h_addrtype;
(*addr_con).sin_port = htons(PORT_NO);
(*addr_con).sin_addr.s_addr = *(long*)host_entity->h_addr;
return ip;
}
// Resolves the reverse lookup of the hostname
char* reverse_dns_lookup(char* ip_addr) {
struct sockaddr_in temp_addr;
socklen_t len;
char buf[NI_MAXHOST], *ret_buf;
temp_addr.sin_family = AF_INET;
temp_addr.sin_addr.s_addr = inet_addr(ip_addr);
len = sizeof(struct sockaddr_in);
if (getnameinfo((struct sockaddr*)&temp_addr, len, buf, sizeof(buf), NULL, 0,
NI_NAMEREQD)) {
// printf("Could not resolve reverse lookup of hostname\n");
return NULL;
}
ret_buf = (char*)malloc((strlen(buf) + 1) * sizeof(char));
strcpy(ret_buf, buf);
return ret_buf;
}
// Driver Code
int main(int argc, char* argv[]) {
int sockfd;
char *ip_addr, *reverse_hostname;
struct sockaddr_in addr_con;
int addrlen = sizeof(addr_con);
char net_buf[NI_MAXHOST];
int i = 0;
for (int i = 1; i < 255; ++i) {
char ip[80];
sprintf(ip, "192.168.2.%d", i);
ip_addr = dns_lookup(ip, &addr_con);
if (ip_addr == NULL) {
// printf("\nDNS lookup failed! Could not resolve hostname!\n");
continue;
}
reverse_hostname = reverse_dns_lookup(ip_addr);
if (reverse_hostname == NULL) {
// printf("\nDNS lookup failed! Could not resolve hostname!\n");
continue;
}
// printf("\nTrying to connect to '%s' IP: %s\n",ip, ip_addr);
printf("\nReverse Lookup domain: %s", reverse_hostname);
printf("\n %s \n", ip);
}
return 0;
}
result:
Reverse Lookup domain: router.asus.com
192.168.2.1
Reverse Lookup domain: DESKTOP-CMK0J2S
192.168.2.10
Reverse Lookup domain: User255
192.168.2.14
Very vague question, there is no single "find all devices" feature to Windows, wireless or even networking in general. You need to scan fer certain services like netbios (139), UPNP, etc. Also, none of this is specific to wireless conenctions.