Skip to content
Snippets Groups Projects
Commit 2c0fed23 authored by Neesergparajuli's avatar Neesergparajuli
Browse files

Set it up so it displays IP, credit to beej's guide http://beej.us/guide/bgnet/

parent 7a726c5e
No related branches found
No related tags found
No related merge requests found
server 0 → 100755
File added
server.c 0 → 100644
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <netinet/in.h>
#include <unistd.h>
int main(int argc, char *argv[]){
struct addrinfo info, *res, *p;
int status;
char ipstr[INET6_ADDRSTRLEN];
if (argc <2){
fprintf(stderr,"ERROR, no port provided\n");//to check if there is no port provided at start
exit(1);
}
memset(&info, 0, sizeof(info));
info.ai_family = AF_UNSPEC; ///sets it to IPv4
info.ai_socktype = SOCK_STREAM; //TCP connection stream oriented
info.ai_flags = AI_PASSIVE; //use my current IP adress
if((status = getaddrinfo(NULL, argv[1], &info, &res) != 0)){
fprintf(stderr,"ERROR, no port provided\n");//to check if getaddrinfo gets any addrinfos
exit(1);
}
for (p = res; p!= NULL; p = p->ai_next)
{
void *addr;
char *ipver;
if (p->ai_family == AF_INET) { // IPv4
struct sockaddr_in *ipv4 = (struct sockaddr_in *)p->ai_addr;
addr = &(ipv4->sin_addr);
ipver = "IPv4";
} else { // IPv6
struct sockaddr_in6 *ipv6 = (struct sockaddr_in6 *)p->ai_addr;
addr = &(ipv6->sin6_addr);
ipver = "IPv6";
}
inet_ntop(p->ai_family, addr, ipstr, sizeof ipstr);
printf(" %s: %s\n", ipver, ipstr);
}
freeaddrinfo(res);
return 0;
}
\ No newline at end of file
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment