I did read it, and I didn't get it. I don't get why the *-operator is used twice..
I tried to write some code (which I guess clearly shows I don't know what I'm doing!), and it fails on the bind procedure. What I want the app to do is to create a socket, and then get some info on the host. Should I perhaps use connect too? I guess the bind fails due to the server I'm testing it on (my own). Do I need to run a service on the port to be able to get any kind of response? Anyway, here's the code:
Code:
#include <stdio.h>
#include <netdb.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#define PORT 6891 // < 1024 = root only
extern int errno;
extern int h_errno;
int main(int argc, char *argv[]) {
char *ip;
int newsock, peer, peer_len;
struct hostent *host;
struct sockaddr_in address;
if(argc != 2) {
printf("usage: %s <host or ip>\n", argv[0]);
exit(-1);
}
/* if argument is a host, get the IP. if IP is supplied, it's ok! */
if((host = gethostbyname(argv[1])) == NULL) {
herror("ERROR on getting host:");
exit(-1);
} else {
/* get the IP from the host */
ip = inet_ntoa(*(struct in_addr*)host->h_addr_list[0]);
}
printf("%s\n", ip);
/* AF_INET = ARPA Internet protocols */
if((newsock = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
herror("ERROR (on socket)");
exit(-1);
}
/* setting up the struct */
address.sin_family = AF_INET;
address.sin_addr.s_addr = *ip; /* getting the IP into the struct */ /* WRONG ??? */
address.sin_port = htons(PORT); /* getting the port to connect to */
address.sin_family = AF_INET; /* host byte order */
memset(&(address.sin_zero), '\0', 8);
/* bind to the port with the descriptor */
if(bind(newsock, (struct sockaddr *)&address, sizeof(struct sockaddr)) == -1) {
herror("ERROR (on bind)");
exit(-1);
}
peer_len = sizeof(address);
/* get some info on the host */
if((peer = getpeername(newsock, (struct sockaddr *)&address, &peer_len)) == -1) {
herror("ERROR (on getpeername)");
exit(-1);
}
return 0;
}