This is some C code I have to simply test the internet connection. Any comments/tips on efficiency and refactoring this program down would be greatly appreciated.
int testConnection(void)
{
int status;
struct addrinfo host_info;
struct addrinfo *host_info_list;
memset(&host_info, 0, sizeof host_info);
#ifdef DEBUG
fprintf(stdout,"Setting up the structs...");
#endif
host_info.ai_family = AF_UNSPEC; // IP version not specified. Can be both.
host_info.ai_socktype = SOCK_STREAM; // Use SOCK_STREAM for TCP or SOCK_DGRAM for UDP.
status = getaddrinfo("www.google.com", "80", &host_info, &host_info_list);
if (status != 0) fprintf(stdout, "Address info error:: %s\n", gai_strerror(status));
#ifdef DEBUG
fprintf(stdout, "Creating a socket...\n");
#endif
int socketfd ;
socketfd = socket(host_info_list->ai_family, host_info_list->ai_socktype, host_info_list->ai_protocol);
if (socketfd == -1) fprintf(stderr, "Socket error\n");
#ifdef DEBUG
fprintf(stdout, "Connecting...");
#endif
status = connect(socketfd, host_info_list->ai_addr, host_info_list->ai_addrlen);
if (status < 0) fprintf(stderr, "Error while connecting.\n");
#ifdef DEBUG
fprintf(stdout, "Sending message...\n");
#endif
const char *msg = "GET / HTTP/1.1\nhost: www.google.com\n\n";
int len = strlen(msg);
ssize_t bytes_sent = send(socketfd, msg, len, 0);
if (bytes_sent == 0) fprintf(stderr, "No bytes sent.\n");
#ifdef DEBUG
fprintf(stdout, "Bytes sent: %d\n", bytes_sent);
fprintf(stdout, "Waiting to recieve data...\n");
#endif
char incomming_data_buffer[1000];
ssize_t bytes_recieved = recv(socketfd, incomming_data_buffer,1000, 0);
// If no data arrives, the program will just wait here until some data arrives.
if (bytes_recieved == 0) fprintf(stderr, "Host shut down.\n");
if (bytes_recieved == -1) fprintf(stderr, "Recieve error.\n");
incomming_data_buffer[bytes_recieved - 2] = '\0';
#ifdef DEBUG
fprintf(stdout, "Bytes recieved: %d\n", bytes_recieved);
fprintf(stdout, "%s\n", incomming_data_buffer);
fprintf(stdout, "Receiving complete. Closing socket...\n");
#endif
freeaddrinfo(host_info_list);
close(socketfd);
#ifdef DEBUG
fprintf(stdout, "Socket closed.\n");
#endif
return 0;
}