terça-feira, 29 de dezembro de 2009

listen for browser

#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <netdb.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>


int
main (int argc, char ** argv)
{
  char * html, buf[BUFSIZ];
  int socket_fd, ret_status, sock_client_fd, pid;
  struct sockaddr_in socket_name, sock_client;
  struct hostent * host_info;

  /* Create a socket */
  socket_fd = socket (PF_INET, SOCK_STREAM, 0);

  /* Store the socket name at socket addres */
  socket_name.sin_family = AF_INET;

  /* addr of server (me) */
  // socket_name.sin_addr.s_addr = INADDR_ANY;
  inet_aton (argv[1], & socket_name.sin_addr.s_addr);

  /* use port 80 */
  socket_name.sin_port = htons (80);

  /* bind socket to an addr */
  ret_status = bind (socket_fd, (struct sockaddr *) & socket_name, 
      sizeof (socket_name));
  if (ret_status == -1) {
 perror ("bind");
 return -1;
  }
  printf ("binded\n");
  /* listen for connections */
  listen (socket_fd, 3);
  printf ("listen\n");

  /* accept new connections */
  ret_status = (int) sizeof sock_client;
  while ((sock_client_fd = accept (socket_fd, (struct sockaddr *) & sock_client, 
           & ret_status)) > 0) {

   /* print the ip of client */
   printf ("\n\nreceived connection from %s\n", inet_ntoa (sock_client.sin_addr.s_addr));

   /* wait GET */
   printf ("reading from client\n");
   while ((ret_status = read (sock_client_fd, buf, BUFSIZ)) > 0) {
  write (1, buf, ret_status);
  if ((strstr (buf, "GET")) != NULL)
    break;
   }
   if (ret_status == -1) {
  perror ("reading from browser");
  return -1;
   }

   /* send an ok */ 
   printf ("sending DATA\n");
   html = 
  "HTTP/1.1 200 OK\n"
  "Accept-Ranges: Bytes\n"
  "Content-Length: 76\n"
  "Content-Type: text/html; charset=UTF-8\n"
  "\n"
  "<html>"
  "<head><title>Hello World</title></head>"
  "<body>Hello World</body>"
  "</html>";

   ret_status = write (sock_client_fd, html, strlen (html));
   if (ret_status == -1) {
  perror ("sending ok");
  return -1;
   }

  }

  return 0;
}

alias getmyip='sudo ifconfig eth0 | grep -w addr | cut -f2 -d: | cut -f1 -d" "'
compile: gcc -o listen-browser listen-browser.c
run sudo ./listen-browser $(getmyip)
this doesn't work properly yet, I just post to save the code (:

Nenhum comentário:

Postar um comentário