Hi, I wrote this code
Code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
int main() {
char buffer[1000] = "";
int fd = socket(AF_INET, SOCK_STREAM, 0);
perror("socket");
int i = 0, connfd;
struct addrinfo *hints;
struct addrinfo *res = malloc(sizeof(res));
struct sockaddr *incoming;
res->ai_addr = malloc(sizeof(res->ai_addr));
hints->ai_flags = AI_PASSIVE;
hints->ai_family = AF_INET;
hints->ai_socktype = SOCK_STREAM;
i = getaddrinfo(NULL, "80", hints, &res);
perror("getaddrinfo");
for(i = 0; i < 1; i++) {
printf("%c", res->ai_addr->sa_data[i]);
}
i = bind(fd, res->ai_addr, res->ai_addrlen);
perror("bind");
listen(fd, 5);
socklen_t sizeofIncoming = sizeof(incoming);
while(connfd = accept(fd, incoming, &sizeofIncoming)) {
perror("accept");
read(connfd, buffer, sizeof(buffer));
write(connfd, "HTTP/1.1 200 OK\nContent-Length: 29\nContent-Type: text/html\n\n", 65);
sprintf(buffer, "Your ip is: %s", incoming->sa_data);
write(connfd, buffer, 24);
printf("SA_DATA\n%s", incoming->sa_data);
printf("END OF SA_DATA\n");
close(connfd);
}
return 0;
}
I have four questions
1) Why do I have to malloc *res but not *hints? When I tried to access *res variables it gave seg fault error
2) Why the line
Code:
printf("%c", res->ai_addr->sa_data[i]);
doesn't print anything? is sa_data empty? why? isn't it supposed to contain an ip address?
3) In the lines
Code:
sprintf(buffer, "Your ip is: %s", incoming->sa_data);
write(connfd, buffer, 24);
I try to write "Your ip is: *some ip*" but the browser shows "YourYour ip is: keep-alive"
Also, what snprintf prints as incoming->sa_data differs from what
Code:
printf("SA_DATA\n%s", incoming->sa_data);
prints
4) if I change *hints into hints, change all the hints-> to hints. and in the getaddrinfo put a & before hints, it stops working why?
Thanks in advanced