Exemplo n.º 1
0
void Print_getaddrinfo_list(struct addrinfo *list_head) {
	struct addrinfo *p = list_head;
	char info[MAXSTR];
	char tmpstr[MAXSTR];
	err_msg ("(%s) listing all results of getaddrinfo", prog_name);	
	while (p != NULL) {
		info[0]='\0';

		int ai_family = p->ai_family;
		if (ai_family == AF_INET)
			strcat(info, "AF_INET  ");
		else if (ai_family == AF_INET6)
			strcat(info, "AF_INET6 ");
		else
			{ sprintf(tmpstr, "(fam=%d?) ",ai_family); strcat(info, tmpstr); }

		int ai_socktype = p->ai_socktype;
		if (ai_socktype == SOCK_STREAM)
			strcat(info, "SOCK_STREAM ");
		else if (ai_socktype == SOCK_DGRAM)
			strcat(info, "SOCK_DGRAM  ");
		else if (ai_socktype == SOCK_RAW)
			strcat(info, "SOCK_RAW    ");
		else
			{ sprintf(tmpstr, "(sock=%d?) ",ai_socktype); strcat(info, tmpstr); }

		int ai_protocol = p->ai_protocol;
		if (ai_protocol == IPPROTO_UDP)
			strcat(info, "IPPROTO_UDP ");
		else if (ai_protocol == IPPROTO_TCP)
			strcat(info, "IPPROTO_TCP ");
		else if (ai_protocol == IPPROTO_IP)
			strcat(info, "IPPROTO_IP  ");
		else
			{ sprintf(tmpstr, "(proto=%d?) ",ai_protocol); strcat(info, tmpstr); }

		char text_addr[INET6_ADDRSTRLEN];
		if (ai_family == AF_INET)
			Inet_ntop(ai_family, &(((struct sockaddr_in *)p->ai_addr)->sin_addr), text_addr, sizeof(text_addr));
		else if (ai_family == AF_INET6)
			Inet_ntop(ai_family, &(((struct sockaddr_in6 *)p->ai_addr)->sin6_addr), text_addr, sizeof(text_addr));
		else
			strcpy(text_addr, "(addr=?)");
		//Inet_ntop(AF_INET6, p->ai_addr, text_addr, sizeof(text_addr));
		strcat(info, text_addr);
		strcat(info, " ");

		if (p->ai_canonname != NULL) {
			strcat(info, p->ai_canonname);
			strcat(info, " ");
		}
			
		err_msg ("(%s) %s", prog_name, info);
		p = p->ai_next;
	}
}
Exemplo n.º 2
0
int
main(int argc, char **argv)
{
   int               listenfd, connfd;
   socklen_t      clilen, n;
   struct sockaddr_in   servaddr, cliaddr;
   char           buff[MAXLINE];
   time_t            ticks;
   FILE *fp;

   listenfd = Socket(AF_INET, SOCK_STREAM, 0);

   bzero(&servaddr, sizeof(servaddr));
   servaddr.sin_family      = AF_INET;
   servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
   servaddr.sin_port        = htons(13);  /* daytime server */

   Bind(listenfd, (SA *) &servaddr, sizeof(servaddr));

   Listen(listenfd, LISTENQ);

   if ((fp = fopen("np09s_hw1_serv.log", "a")) == NULL) {
      printf("log file open error!\n");
      exit(0);
   };

   for ( ; ; ) {
      clilen = sizeof(cliaddr);
      connfd = Accept(listenfd, (SA *) &cliaddr, &clilen);
      ticks = time(NULL);
      fprintf(fp, "===================\n");
      fprintf (fp, "%.24s: connected from %s, port %d\n",
            ctime(&ticks),
            Inet_ntop(AF_INET, &cliaddr.sin_addr, buff, sizeof (buff)),
            ntohs(cliaddr.sin_port));
      srand((int) ticks);
      n = Read(connfd, buff, sizeof(buff));
      buff[n] = 0;
      fprintf(fp, "id = %s\n", buff);
      ticks = time(NULL);
      snprintf(buff, sizeof(buff), "%.24s\r\n", ctime(&ticks));
      Write(connfd, buff, strlen(buff));
      fprintf (fp, "%.24s: disconnected from %s, port %d\n",
            ctime(&ticks),
            Inet_ntop(AF_INET, &cliaddr.sin_addr, buff, sizeof (buff)),
            ntohs(cliaddr.sin_port));
      fflush(fp);

      Close(connfd);
   }
}
Exemplo n.º 3
0
int
main(int argc, char **argv)
{
	int					listenfd, connfd;
	socklen_t			len;
	struct sockaddr_in	servaddr, cliaddr;
	char				buff[MAXLINE];
	time_t				ticks;

	listenfd = Socket(AF_INET, SOCK_STREAM, 0);

	bzero(&servaddr, sizeof(servaddr));
	servaddr.sin_family      = AF_INET;
	servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
	servaddr.sin_port        = htons(13);	/* daytime server */

	Bind(listenfd, (SA *) &servaddr, sizeof(servaddr));

	Listen(listenfd, LISTENQ);

	for ( ; ; ) {
		len = sizeof(cliaddr);
		connfd = Accept(listenfd, (SA *) &cliaddr, &len);
		printf("connection from %s, port %d\n",
			   Inet_ntop(AF_INET, &cliaddr.sin_addr, buff, sizeof(buff)),
			   ntohs(cliaddr.sin_port));

        ticks = time(NULL);
        snprintf(buff, sizeof(buff), "%.24s\r\n", ctime(&ticks));
        Write(connfd, buff, strlen(buff));

		Close(connfd);
	}
}
Exemplo n.º 4
0
int main(int argc, char **argv)
{
	char			*ptr, **pptr;
	char			str[INET_ADDRSTRLEN];
	struct hostent	*hptr;

	while (--argc > 0) {
		ptr = *++argv;
		if ( (hptr = gethostbyname(ptr)) == NULL) {
			err_msg("gethostbyname error for host: %s: %s",
					ptr, hstrerror(h_errno));
			continue;
		}
		printf("official hostname: %s\n", hptr->h_name);

		for (pptr = hptr->h_aliases; *pptr != NULL; pptr++)
			printf("\talias: %s\n", *pptr);

		switch (hptr->h_addrtype) {
		case AF_INET:
			pptr = hptr->h_addr_list;
			for ( ; *pptr != NULL; pptr++)
				printf("\taddress: %s\n",
					Inet_ntop(hptr->h_addrtype, *pptr, str, sizeof(str)));
			break;

		default:
			err_ret("unknown address type");
			break;
		}
	}
	exit(0);
}
Exemplo n.º 5
0
Arquivo: in_addr.c Projeto: kkaneda/vm
char *
InAddr_to_string ( in_addr_t x )
{
	struct in_addr y;
	char * retval = ( char * ) Malloc ( INET_ADDRSTRLEN );

	y.s_addr = x;
	Inet_ntop ( AF_INET, ( const void* ) &y, retval, INET_ADDRSTRLEN );

	return retval;;
}
Exemplo n.º 6
0
void
dg_echo(int sockfd, SA *pcliaddr, socklen_t clilen)
{
    int						flags;
    const int				on = 1;
    socklen_t				len;
    ssize_t					n;
    char					mesg[MAXLINE], str[INET6_ADDRSTRLEN],
                            ifname[IFNAMSIZ];
    struct in_addr			in_zero;
    struct unp_in_pktinfo	pktinfo;

#ifdef	IP_RECVDSTADDR
    if (setsockopt(sockfd, IPPROTO_IP, IP_RECVDSTADDR, &on, sizeof(on)) < 0)
        err_ret("setsockopt of IP_RECVDSTADDR");
#endif
#ifdef	IP_RECVIF
    if (setsockopt(sockfd, IPPROTO_IP, IP_RECVIF, &on, sizeof(on)) < 0)
        err_ret("setsockopt of IP_RECVIF");
#endif
    bzero(&in_zero, sizeof(struct in_addr));	/* all 0 IPv4 address */

    for ( ; ; )
    {
        len = clilen;
        flags = 0;
        n = Recvfrom_flags(sockfd, mesg, MAXLINE, &flags,
                           pcliaddr, &len, &pktinfo);
        printf("%d-byte datagram from %s", n, Sock_ntop(pcliaddr, len));
        if (memcmp(&pktinfo.ipi_addr, &in_zero, sizeof(in_zero)) != 0)
            printf(", to %s", Inet_ntop(AF_INET, &pktinfo.ipi_addr,
                                        str, sizeof(str)));
        if (pktinfo.ipi_ifindex > 0)
            printf(", recv i/f = %s",
                   If_indextoname(pktinfo.ipi_ifindex, ifname));
#ifdef	MSG_TRUNC
        if (flags & MSG_TRUNC)	printf(" (datagram truncated)");
#endif
#ifdef	MSG_CTRUNC
        if (flags & MSG_CTRUNC)	printf(" (control info truncated)");
#endif
#ifdef	MSG_BCAST
        if (flags & MSG_BCAST)	printf(" (broadcast)");
#endif
#ifdef	MSG_MCAST
        if (flags & MSG_MCAST)	printf(" (multicast)");
#endif
        printf("\n");

        Sendto(sockfd, mesg, n, 0, pcliaddr, len);
    }
}
Exemplo n.º 7
0
void
inet6_srcrt_print(void *ptr)
{
	int			i, segments;
	char			str[INET6_ADDRSTRLEN];

	segments = Inet6_rth_segments(ptr);
	printf("received source route: ");
	for (i = 0; i < segments; i++)
		printf("%s ", Inet_ntop(AF_INET6, Inet6_rth_getaddr(ptr, i),
								str, sizeof(str)));
	printf("\n");
}
Exemplo n.º 8
0
void getAllIP()
{
	int count;
	char name[30];
	struct hostent *hp;
	
	for(count=0;count<10;count++)
	{
		sprintf(name, "vm%d", count+1);
		hp=gethostbyname(name);
		char **pptr=hp->h_addr_list;
		Inet_ntop(hp->h_addrtype, *pptr, ip_array[count], sizeof(ip_array));
	}
}
Exemplo n.º 9
0
int
main(int argc, char **argv)
{
    char			*ptr, **pptr;
    char			str[INET_ADDRSTRLEN];
    struct hostent	*hptr;

    while (--argc > 0) {
        ptr = *++argv;
        if ( ( hptr = gethostbyname(ptr)) == NULL) {
            err_msg("gethostbyname error for host: %s: %s",
                    ptr, hstrerror(h_errno));
            continue;
        }
        printf("official hostname: %s\n", hptr->h_name);

        for ( pptr = hptr->h_aliases; *pptr != NULL; pptr++)
            printf("	alias: %s\n", *pptr);

        switch ( hptr->h_addrtype) {
        case AF_INET:
#ifdef	AF_INET6
        case AF_INET6:
#endif
            pptr = hptr->h_addr_list;
            for ( ; *pptr != NULL; pptr++) {
                printf("\taddress: %s\n",
                       Inet_ntop( hptr->h_addrtype, *pptr, str, sizeof(str)));

                if ( ( hptr = gethostbyaddr(*pptr, hptr->h_length,
                                            hptr->h_addrtype)) == NULL) {
                    printf("\t(gethostbyaddr failed)\n");
                    break;
                }
                else if ( hptr->h_name != NULL)
                    printf("\tname = %s\n", hptr->h_name);
                else
                    printf("\t(no hostname returned by gethostbyaddr)\n");
            }
            break;

        default:
            err_ret("unknown address type");
            break;
        }
    }
    exit(0);
}
Exemplo n.º 10
0
void msg_recv(int sockfd, char *recvdMsg, char *srcIPAddrCanonical, int *srcPort)
{

    struct sockaddr_un odrSockAddr;
    AppOdrPacket packet;
    int len = sizeof(struct sockaddr_un );

    memset(&odrSockAddr, 0, sizeof(odrSockAddr));
    memset(&packet, 0, sizeof (packet));

    recvfrom(sockfd, (char *)&packet, sizeof(packet), 0, (struct sockaddr *)&odrSockAddr, &len);   

    strcpy(recvdMsg, packet.msgData);
    Inet_ntop(AF_INET, &(packet.destIP), srcIPAddrCanonical, INET_ADDRSTRLEN);
    *srcPort = packet.port;
}
Exemplo n.º 11
0
int main(int argc, char *argv[]) {
    int proxyfd, clifd;
    struct sockaddr_in proxyaddr, cliaddr;
    socklen_t cliaddrlen;

    /* initialize the socket as a server */
    proxyfd = Socket(AF_INET, SOCK_STREAM, 0);
    bzero(&proxyaddr, sizeof(proxyaddr));
    proxyaddr.sin_family = AF_INET;
    proxyaddr.sin_addr.s_addr = htonl(INADDR_ANY);
    proxyaddr.sin_port = htons(PROXY_PORT);
    Bind(proxyfd, (struct sockaddr *)&proxyaddr, sizeof(proxyaddr));
    Listen(proxyfd, 5);

    /* infinite loop waiting for and processing requests */
    char cliaddrip[INET_ADDRSTRLEN];
    int pid;
    while (1) {
	cliaddrlen = sizeof(cliaddr);
	clifd = Accept(proxyfd, (struct sockaddr *)&cliaddr, &cliaddrlen);
	Inet_ntop(AF_INET, &cliaddr.sin_addr, cliaddrip, INET_ADDRSTRLEN);

	fprintf(stdout, "---Request comes, IP=%s\n", cliaddrip);

	/* process the request in a subprocess */
	if ((pid=fork()) == 0) {
	    pid = getpid();
	    fprintf(stdout, "---pid=%d, Process the request in a subprocess\n", pid);

	    fprintf(stdout, "---pid=%d, Close proxy socket in the subprocess\n", pid);
	    Close(proxyfd);

	    do_proxy(clifd, &cliaddr, pid);

	    fprintf(stdout, "---pid=%d, Close the client socket in the subprocess\n", pid);
	    Close(clifd);

	    fprintf(stdout, "---pid=%d, Subprocess exits\n", pid);
	    exit(0);
	}

	fprintf(stdout, "---Close the client socket in the parent process\n");
	Close(clifd);
    }

    return 0;
}
Exemplo n.º 12
0
int
main(int argc, char **argv)
{
	char			*ptr, **pptr, **listptr, buf[INET6_ADDRSTRLEN];
	char			*list[100];
	int				i, addrtype, addrlen;
	struct hostent	*hptr;

	while (--argc > 0) {
		ptr = *++argv;
		if ( (hptr = gethostbyname(ptr)) == NULL) {
			err_msg("gethostbyname error for host: %s: %s",
					ptr, hstrerror(h_errno));
			continue;
		}
		printf("official host name: %s\n", hptr->h_name);

		for (pptr = hptr->h_aliases; *pptr != NULL; pptr++)
			printf("	alias: %s\n", *pptr);
		addrtype = hptr->h_addrtype;
		addrlen = hptr->h_length;

			/* copy array of pointers, so we can call gethostbyaddr() */
		for (i = 0, listptr = hptr->h_addr_list; *listptr != NULL; listptr++) {
			list[i++] = *listptr;
		}
		list[i] = NULL;

		for (listptr = list; *listptr != NULL; listptr++) {
			printf("\taddress: %s\n",
				   Inet_ntop(addrtype, *listptr, buf, sizeof(buf)));

			if ( (hptr = gethostbyaddr(*listptr, addrlen, addrtype)) == NULL)
				printf("\t\t(gethostbyaddr failed)\n");
			else if (hptr->h_name != NULL)
				printf("\t\tname = %s\n", hptr->h_name);
			else
				printf("\t\t(no hostname returned by gethostbyaddr)\n");

			printf("\t\tofficial host name: %s\n", hptr->h_name);

			for (pptr = hptr->h_aliases; *pptr != NULL; pptr++)
				printf("\t\talias: %s\n", *pptr);
		}
	}
}
Exemplo n.º 13
0
int receiveREQ( int servfd, struct sockaddr_in* pcliaddr, socklen_t* plen )
{
  char clientIP[INET_ADDRSTRLEN];
  printf( "waiting for request...\n" );
  //receiving a null terminated filename
again:
  if( recvfrom( servfd, &recvPacket, sizeof(recvPacket), 0, (SA*)pcliaddr, plen  ) < 0 )
    if(errno == EWOULDBLOCK) goto again;
    else err_sys( "recvfrom for REQ error" );
  if( recvPacket.type != REQ ) {
    errno = EMEDIUMTYPE;
    return -1;
  } 

  Inet_ntop(AF_INET, &pcliaddr->sin_addr, clientIP, sizeof(clientIP));
  printf( "server reads request for '%s' from %s:%d\n", recvPacket.msg, clientIP, ntohs(pcliaddr->sin_port) );
  //open file and open error
  return open( recvPacket.msg, O_RDONLY );
}
int
main(int argc, char **argv) {

    int listenfd, connfd;
    socklen_t len;
    struct sockaddr_in servaddr, cliaddr;
    char buff[MAXLINE];
    time_t ticks;

    listenfd = Socket(AF_INET, SOCK_STREAM, 0);

    bzero(&servaddr, sizeof (servaddr));
    servaddr.sin_family = AF_INET;
    servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
    servaddr.sin_port = htons(9997); /* test*/

    Bind(listenfd, (SA *) & servaddr, sizeof (servaddr));

    Listen(listenfd, LISTENQ);
    puts("listening...");

    for (;;) {
        len = sizeof (cliaddr);
        connfd = Accept(listenfd, (SA *) & cliaddr, &len);
        printf( "connection from %s, port %d\n",
                Inet_ntop(AF_INET, &cliaddr.sin_addr, buff, sizeof (buff)),
                ntohs(cliaddr.sin_port));

        ticks = time(NULL);
        snprintf(buff, sizeof (buff), "%.24s\r\n", ctime(&ticks));

        //Write(connfd, buff, strlen(buff)); // normal version, write at once
        int i; // call Write for each one byte
        for (i = 0; i < strlen(buff); ++i) {
            Write(connfd, &buff[i], 1);
        }
        printf( "writes: %d\n", i);
        Close(connfd);
    }
}
Exemplo n.º 15
0
int main(int argc, char **argv) {

					//start of the address from argv
	char 			*ptr, **pptr;
	char 			str[INET_ADDRSTRLEN];
	struct hostent *hptr;

	while(--argc > 0) {

		ptr = *++argv;

		//gethostbyname is a function to get the ip from DNS - numeric tpye
		if((hptr = gethostbyname(ptr)) == NULL) {

			err_msg("gethostbyname error for host: %s: %s", ptr, hstrerror(h_errno));
			continue;
		}
		//This is the “official” name of the host.
		printf("official hostname: %s\r\n", hptr->h_name);

		//These are alternative names for the host, represented as a null-terminated vector of strings.
		for(pptr = hptr->h_aliases; *pptr != NULL; pptr++) {
			printf("\t alias: %s\r\n", *pptr);
		}


		//pointer to all known IPs for that DNS
		pptr = hptr->h_addr_list; // vector of addresses

		for( ; *pptr != NULL; pptr++) {

			printf("\t Addr %lu \r\n", hptr->h_addr);
			//AF_INET or AF_INET6 lattter is for IPV6
			printf("\t address :%s\r\n", Inet_ntop(hptr->h_addrtype, *pptr, str, sizeof(str)));
		}
	}

	exit(0);
}
Exemplo n.º 16
0
void
dg_echo(int sockfd, SA *pcliaddr, socklen_t clilen)
{
	int				flags;
	const int		on = 1;
	socklen_t		len;
	ssize_t			n;
	char			mesg[MAXLINE], str[INET6_ADDRSTRLEN];
	struct in_addr	dstaddr;

#ifdef	IP_RECVDSTADDR
	Setsockopt(sockfd, IPPROTO_IP, IP_RECVDSTADDR, &on, sizeof(on));
#endif

	for ( ; ; ) {
		len = clilen;
		flags = 0;
		n = Recvfrom_flags(sockfd, mesg, MAXLINE, &flags,
						   pcliaddr, &len, &dstaddr);
		printf("%d-byte datagram from %s", n, Sock_ntop(pcliaddr, len));
		if ((flags & MSG_CTRUNC) == 0)
			printf(", to %s", Inet_ntop(AF_INET, &dstaddr, str, sizeof(str)));
#ifdef	MSG_TRUNC
		if (flags & MSG_TRUNC)	printf(" (datagram truncated)");
#endif
#ifdef	MSG_BCAST
		if (flags & MSG_BCAST)	printf(" (broadcast)");
#endif
#ifdef	MSG_MCAST
		if (flags & MSG_MCAST)	printf(" (multicast)");
#endif
		printf("\n");

		Sendto(sockfd, mesg, n, 0, pcliaddr, clilen);
	}
}
Exemplo n.º 17
0
int main(int argc, char **argv)
{
	getAllIP();

	int count;
	
	for( ; ; )
	{
		printf("\nPlease Choose the Server From VM1 to VM10.\n");
		printf("(1 - 10):");

		int choose;

		scanf("%d", &choose);

		int vm_dest=choose;
		struct hostent *hp;
		
		char ip_src[INET_ADDRSTRLEN];
		char ip_dest[INET_ADDRSTRLEN];

		int result;
		
		char namestr[10];
		
		for(count=0;count<5;count++)
		{
			namestr[count]='\0';
		}

		sprintf(namestr, "vm%d", choose);

		hp=gethostbyname(namestr);

		char **pptr=hp->h_addr_list;
		Inet_ntop(hp->h_addrtype, *pptr, ip_dest, sizeof(ip_dest));
		
		int sockfd;
	
		struct sockaddr_un servaddr;
		struct sockaddr_un cliaddr;

		sockfd=Socket(AF_LOCAL, SOCK_DGRAM, 0);

		char temp_file[]="tmp_XXXXXX";
		mkstemp(temp_file);

		unlink(temp_file);
		
		bzero(&cliaddr, sizeof(cliaddr));
		cliaddr.sun_family=AF_LOCAL;
		strcpy(cliaddr.sun_path, temp_file);
	
		Bind(sockfd, (SA *)&cliaddr, sizeof(cliaddr));

		bzero(&servaddr, sizeof(servaddr));
		servaddr.sun_family=AF_LOCAL;
		strcpy(servaddr.sun_path, ODR_PATH);
	
		//client ip vm
		struct hwa_info *hwa;
		struct hwa_info *hwahead;

		struct sockaddr *sa;
		char *ptr;

		for(hwahead=hwa=Get_hw_addrs(); hwa!=NULL;hwa=hwa->hwa_next)
		{
			//we only care about eth0
			if(strcmp(hwa->if_name, "eth0")==0)
			{
				sa=hwa->ip_addr;
				sprintf(ip_src, "%s", Sock_ntop_host(sa, sizeof(*sa)));
			}
		}
		
		//msg_send
		char message[32];
		for(count=0;count<32;count++)
		{
			message[count]='\0';
		}
		sprintf(message, "%s", "\0");

		//char send_packet[50];
		//Sendto(sockfd, send_packet, 50, 0, (SA *)&servaddr, sizeof(servaddr));
		msg_send(sockfd, (SA *)&servaddr, sizeof(servaddr), ip_src, ip_dest, SERV_WKPORT, message, 0);

		char *new_message=(char *)Malloc(32);
		for(count=0;count<32;count++)
		{
			new_message[count]='\0';
		}
		
		char new_ipsrc[SIZE_IP];
		char new_ipdest[SIZE_IP];
		unsigned short new_portsrc;
		unsigned short new_portdest;
		
		result=msg_recv(sockfd, new_message, new_ipsrc, &new_portsrc, new_ipdest, &new_portdest);
		
		if(result==-1)
		{
			printf("##RECV# client at node vm%d timeout on response from vm%d.\n", getVMNum(ip_src)+1, getVMNum(ip_dest)+1);
			
			msg_send(sockfd, (SA *)&servaddr, sizeof(servaddr), ip_src, ip_dest, SERV_WKPORT, message, 1);

			result=msg_recv(sockfd, new_message, new_ipsrc, &new_portsrc, new_ipdest, &new_portdest);

			if(result==-1)
			{
				printf("##RECV# client at node vm%d timeout on response from vm%d.\n", getVMNum(ip_src)+1, getVMNum(ip_dest)+1);
				unlink(temp_file);
				continue;
			}
		}
		
		unlink(temp_file);
	}
}
Exemplo n.º 18
0
void main(int argc, char **argv) {
    int fd, sockfd, temp, n, recv_port, forced_disc;
    struct timeval t;
    struct sockaddr_un cliaddr;
    char serv_node[10], cli_node[10], file_path[40], sendline[1024], recvline[1024], send_ip[20], recv_ip[20];
    struct hostent *host;
    fd_set rset;
    FD_ZERO(&rset);

    strcpy(file_path,"/tmp/upasi_XXXXXX");
    fd = mkstemp(file_path);

    if(fd < 0) {
        printf("Could not create a new file \n");
        exit(-1);       
    }

    sockfd = Socket(AF_LOCAL, SOCK_DGRAM, 0);

    unlink(file_path);

    bzero(&cliaddr,sizeof(cliaddr));
    cliaddr.sun_family = AF_LOCAL;
    strcpy(cliaddr.sun_path, file_path);
    Bind(sockfd, (struct sockaddr *)&cliaddr, SUN_LEN(&cliaddr));

    printf("Before getting the cli_node \n");
    get_client_node(cli_node);
    printf("Client node is %s\n", cli_node);
    
    while(1)
    {
        forced_disc = 0;
        strcpy(serv_node,"");
        printf("Choose a VM from vm1 to vm10 as a server node:\n");
        scanf("%s", serv_node);
        if(strcmp(serv_node,"exit") == 0) {
            break;
        }

        if((host = gethostbyname(serv_node)) == NULL) {
            printf("Invalid input\n");
            continue;
        }

        if(strncmp(serv_node,"vm",2) != 0) {
            printf("Invalid input\n");
            continue;
        }

        printf("The vm selected is %s\n", serv_node);
        strcpy(send_ip,"");
        Inet_ntop(AF_INET, (void*)host->h_addr, send_ip, 20);
        printf("IP of the selected host is %s\n", send_ip);

        strcpy(sendline,"time");        

send_message:
        printf("Client at node %s sending request to server at %s\n", cli_node, serv_node);
        printf("Preparing to send message \n");
        msg_send(sockfd, send_ip, SERV_PORT_NO, sendline, 0);

        FD_SET(sockfd, &rset);
        t.tv_sec = 8;
        t.tv_usec = 0;
        Select(sockfd+1, &rset, NULL, NULL, &t);

        if(FD_ISSET(sockfd, &rset)) {
            msg_recv(sockfd, recvline, recv_ip, &recv_port);
            printf("Client at node %s: received from %s %s\n", cli_node,serv_node, recvline);
        }
        else {
            if(forced_disc == 0) {
                forced_disc = 1;
                printf("Client at node %s: timeout on response from %s\n", cli_node, serv_node);
                goto send_message;
            }
            else {
                printf("Forced discovery unsuccessful \n");
                continue;
            }
        }
    }

    unlink(cliaddr.sun_path);
    exit(0);
}
Exemplo n.º 19
0
int main(int argc,char**argv)
{
	int listenfd, connfd, n;
	socklen_t			len;

	char buffer[MAXLINE];
	char writeBuffer[MAXLINE];
	char buff[MAXLINE];
	
	//char errorMessage[] = "DENIED";

	char username[50];
	char pass[50];
	
	struct sockaddr_in servaddr, cliaddr;

	if(argc != 2) //verifies number of command-line args; two in this instance
		err_quit("usage: <program name> <Port Number> ");

	listenfd = Socket(AF_INET, SOCK_STREAM, 0); //create socket

	bzero(&servaddr,sizeof(servaddr));
	servaddr.sin_family 	=AF_INET;
	servaddr.sin_addr.s_addr=htonl(INADDR_ANY);
	servaddr.sin_port	=htons(atoi(argv[1]));

	printf("\nStart");
	Bind(listenfd, (SA *) &servaddr,sizeof(servaddr));

	printf("\nListening...");
	Listen(listenfd, LISTENQ);


	for( ; ; )
	{
		len = sizeof(cliaddr);
		connfd = Accept(listenfd, (SA *) &cliaddr, &len);
		printf("\nAccepted\n");

		while( (n = read(connfd, buffer, MAXLINE)) > 0)
		{
			//exception has occured
			if(n<0)
			{
				break;
			}
			if(strstr(buffer, "\r\n\r\n") != NULL)
			{
				sscanf(buffer, "username: %s password: %s\r\n\r\n", username, pass);
				break;
			}
		}
		if(n<0)
		{
			break;
		}
		//printf("%s",buffer);
		//printf("pass %s",pass);

		//authenticate user
		if(strstr(username, "admin") != NULL && strstr(pass, "pass") != NULL) {
			
			Inet_ntop(AF_INET, &cliaddr.sin_addr, buff, sizeof(buff));

			snprintf(writeBuffer, sizeof(writeBuffer), "PROCEED, IP: %s, Port: %d\r\n\r\n", buff , ntohs(cliaddr.sin_port) );

			Write(connfd, writeBuffer, strlen(writeBuffer));
			//Write(connfd, successMessage, strlen(successMessage));
		} else {
			snprintf(writeBuffer, sizeof(writeBuffer), "DENIED\n\r\n");
			Write(connfd, writeBuffer, strlen(writeBuffer));
		}

		printf("\nClose connection");
		Close(connfd);
	}


	return 0;
}
Exemplo n.º 20
0
int
readable_v6(void)
{
#ifdef	IPV6
	int					i, hlen1, hlen2, icmp6len, sport;
	char				buf[MAXLINE];
	char				srcstr[INET6_ADDRSTRLEN], dststr[INET6_ADDRSTRLEN];
	ssize_t				n;
	socklen_t			len;
	struct ip6_hdr		*ip6, *hip6;
	struct icmp6_hdr	*icmp6;
	struct udphdr		*udp;
	struct sockaddr_in6	from, dest;
	struct icmpd_err	icmpd_err;

	len = sizeof(from);
	n = Recvfrom(fd6, buf, MAXLINE, 0, (SA *) &from, &len);

	printf("%d bytes ICMPv6 from %s:",
		   n, Sock_ntop_host((SA *) &from, len));

	ip6 = (struct ip6_hdr *) buf;		/* start of IPv6 header */
	hlen1 = sizeof(struct ip6_hdr);
	if (ip6->ip6_nxt != IPPROTO_ICMPV6)
		err_quit("next header not IPPROTO_ICMPV6");

	icmp6 = (struct icmp6_hdr *) (buf + hlen1);
	if ( (icmp6len = n - hlen1) < 8)
		err_quit("icmp6len (%d) < 8", icmp6len);

	printf(" type = %d, code = %d\n", icmp6->icmp6_type, icmp6->icmp6_code);
/* end readable_v61 */

/* include readable_v62 */
	if (icmp6->icmp6_type == ICMP6_DST_UNREACH ||
		icmp6->icmp6_type == ICMP6_PACKET_TOO_BIG ||
		icmp6->icmp6_type == ICMP6_TIME_EXCEEDED) {
		if (icmp6len < 8 + 40 + 8)
			err_quit("icmp6len (%d) < 8 + 40 + 8", icmp6len);

		hip6 = (struct ip6_hdr *) (buf + hlen1 + 8);
		hlen2 = sizeof(struct ip6_hdr);
		printf("\tsrcip = %s, dstip = %s, next hdr = %d\n",
			   Inet_ntop(AF_INET6, &hip6->ip6_src, srcstr, sizeof(srcstr)),
			   Inet_ntop(AF_INET6, &hip6->ip6_dst, dststr, sizeof(dststr)),
			   hip6->ip6_nxt);
 		if (hip6->ip6_nxt == IPPROTO_UDP) {
			udp = (struct udphdr *) (buf + hlen1 + 8 + hlen2);
			sport = udp->uh_sport;

				/* 4find client's Unix domain socket, send headers */
			for (i = 0; i <= maxi; i++) {
				if (client[i].connfd >= 0 &&
					client[i].family == AF_INET6 &&
					client[i].lport == sport) {

					bzero(&dest, sizeof(dest));
					dest.sin6_family = AF_INET6;
#ifdef	HAVE_SOCKADDR_SA_LEN
					dest.sin6_len = sizeof(dest);
#endif
					memcpy(&dest.sin6_addr, &hip6->ip6_dst,
						   sizeof(struct in6_addr));
					dest.sin6_port = udp->uh_dport;

					icmpd_err.icmpd_type = icmp6->icmp6_type;
					icmpd_err.icmpd_code = icmp6->icmp6_code;
					icmpd_err.icmpd_len = sizeof(struct sockaddr_in6);
					memcpy(&icmpd_err.icmpd_dest, &dest, sizeof(dest));

						/* 4convert type & code to reasonable errno value */
					icmpd_err.icmpd_errno = EHOSTUNREACH;	/* default */
					if (icmp6->icmp6_type == ICMP6_DST_UNREACH) {
						if (icmp6->icmp6_code == ICMP_UNREACH_PORT)
							icmpd_err.icmpd_errno = ECONNREFUSED;
						else if (icmp6->icmp6_code == ICMP_UNREACH_NEEDFRAG)
							icmpd_err.icmpd_errno = EMSGSIZE;
					}
					Write(client[i].connfd, &icmpd_err, sizeof(icmpd_err));
				}
			}
		}
	}
	return(--nready);
#endif
}
Exemplo n.º 21
0
/* This routine does the first phase of the client-server Setup.
 * On successfule return, the out parameter sockfd will have the 
 * connection socket fd.
 * */
int connection_setup(int *sockfd, ifi_t *ifi_array[], int num_ifi,
    circ_buffer_t *rcv_buf, client_config_t *config)
{
  packet_t *send_pkt;
  int n, optval=1;
  char in_packet[PACKET_LEN],client_ip[IP_MAX];	
  struct sockaddr_in serv_addr, cliaddr, tempaddr;
  unsigned int ack_seq;
  unsigned short curr_win;
  bool is_error = FALSE;
  packet_info_t *rcv_pkt_info, *send_pkt_info = calloc(1, sizeof(packet_info_t));
  
  *sockfd = Socket(AF_INET, SOCK_DGRAM, 0);

  if(server_on_same_subnet(config->server_ip,ifi_array, num_ifi, client_ip))
  {	
    printf("server on same subnet, SO_DONTROUTE set\n");
    //printf("client ip set to: %s\n",client_ip);
    setsockopt(*sockfd,SOL_SOCKET, SO_DONTROUTE, &optval, sizeof(optval));
  }	
  //update  cli_ip after if it's on the same host or n/w

  bzero(&cliaddr, sizeof(cliaddr));
  cliaddr.sin_family = AF_INET;
  cliaddr.sin_port = 0;
  inet_pton(AF_INET,client_ip,&cliaddr.sin_addr);
  Bind(*sockfd, (SA*) &cliaddr, sizeof(cliaddr));

  //cli addr and port using getsockname
  int cli_port;
  char cli_ip[IP_MAX];
  socklen_t len = sizeof(tempaddr);
  bzero(&tempaddr, sizeof(tempaddr));
  getsockname(*sockfd, (SA*) &tempaddr, &len);
  Inet_ntop(AF_INET, &tempaddr.sin_addr, cli_ip, IP_MAX);
  printf("[Info]client bound to ip:%s\n",cli_ip);
  cli_port = ntohs(tempaddr.sin_port);

  //connect
  bzero(&serv_addr, sizeof(serv_addr));
  serv_addr.sin_family = AF_INET;
  serv_addr.sin_port = htons(config->server_port);
  Inet_pton(AF_INET, config->server_ip, &serv_addr.sin_addr);
  Connect(*sockfd, (SA *)&serv_addr, sizeof(serv_addr));

  assert(send_pkt_info);

  Signal(SIGALRM, sig_alarm);
  rtt_newpack(&rttinfo);          /* initialize for this packet */

  /* Prepare to send file name */
  send_pkt_info->seq = 0;
  send_pkt_info->ack = 0;
  send_pkt_info->window_size = config->window_size;
  SET_FILE_FLAG(send_pkt_info);
  send_pkt_info->data = strdup(config->file_name);
  send_pkt_info->data_len = strlen(config->file_name) + 1;

  printf("[Info] Sending file name %s to server ..\n", send_pkt_info->data);

sendagain:
  send_pkt_info->timestamp = rtt_ts(&rttinfo);
  send_pkt = build_packet(send_pkt_info);

  Write(*sockfd, (char *)send_pkt, send_pkt_info->data_len+HEADER_SIZE);

  /* set alarm for RTO seconds using setitimer */
  set_alarm(rtt_start(&rttinfo));
  if (sigsetjmp(jmpbuf, 1) != 0)
  {
    if (rtt_timeout(&rttinfo))
    {
      printf("[Error] Timed out Sending File Name, giving Up\n");
      free_pkt_info(send_pkt_info);
      free(send_pkt);
      errno = ETIMEDOUT;
      return -1;
    }
    printf("[Timeout] Retransmitting file name, next RTO:%d ms\n", rttinfo.rtt_rto);
    free(send_pkt);
    goto sendagain;
  }

  /* Now Attempt to read the Port message from the Server */
  while (1)
  {
    if ((n = read(*sockfd, in_packet, PACKET_LEN)) < 0)
    {
      if (errno == EINTR) 
        continue;
      else
        err_sys("[Error] Read Error while waiting for Port number");
    }

    rcv_pkt_info = get_packet_info(in_packet, n);

    if (consume_random_packet(rcv_pkt_info, config->prob_loss, TRUE))
    {
      free_pkt_info(rcv_pkt_info);
      continue;
    }

    if (IS_ACK(rcv_pkt_info) && (rcv_pkt_info->ack == (send_pkt_info->seq+1)))
    {
      break;
    }
    else
    {
      free_pkt_info(rcv_pkt_info);
      continue;
    }
  }

  set_alarm(0);     /* Turn off the Alarm */

  free_pkt_info(send_pkt_info);
  free(send_pkt);

  assert(rcv_pkt_info->data_len == sizeof(short));
  /* Fetch the new port from the server message */
  memcpy(&serv_addr.sin_port, rcv_pkt_info->data, sizeof(short));
  
  printf("[Info] Received new Port number %hu from Server.\n", ntohs(serv_addr.sin_port));

  /* Connect to the new port of the server child process */
  if (connect(*sockfd, (SA *)&serv_addr, sizeof(serv_addr)) < 0) {
    printf("[Error] Connect failure to server child: [%s : %hu]\n", config->server_ip, ntohs(serv_addr.sin_port));
    return -1;
  }

  printf("[Info] Connected to server's child process.\n");

  /* Advance the Circular buffer's read/write pointers to rcv_pkt_info->seq+1.
   * Basically, we are simulating the producer/consumer behavior here, in that we 
   * have written and read from the buffer.
   * Note: The server has to continue the file transfer starting from rcv_pkt_info->seq+1
   * as we will not accept anything lower than this sequence for this session
   * This is similar to the SYN+ACK in TCP
   */
  rcv_buf->next_read_seq = rcv_buf->next_contig_write_seq = rcv_pkt_info->seq+1;
  printf("rcv_buf->next_read_seq = rcv_buf->next_contig_write_seq = %u", rcv_pkt_info->seq+1);

  curr_win = window_size(rcv_buf); 
  ack_seq = NEXT_ACK(rcv_buf); 

  /* Exit if the file does not exist on the server after sending ACK.
   * In the event this ACK is lost, the server ichild timeout mechanism will kick in
   * and eventually it will timeout and give up
   */
  if(is_error = IS_ERR(rcv_pkt_info))
  {
    printf("[Info] Received Error message from server [Seq: %u] Responding with [Ack:%u] [Window Size:%hu]\n", 
        rcv_pkt_info->seq, ack_seq, curr_win);
  }
  else
  {
    printf("[Info] Received Port message [Seq: %u] Responding with [Ack:%u] [Window Size:%hu]\n", 
        rcv_pkt_info->seq, ack_seq, curr_win);
  }

  /* Simulate Loss On Tx */
  if (!consume_random_packet(rcv_pkt_info, config->prob_loss, FALSE))
  {
    send_ack(*sockfd, curr_win, rcv_pkt_info->seq, ack_seq, rcv_pkt_info->timestamp, config->prob_loss);
  }

  free_pkt_info(rcv_pkt_info);
  
  if(is_error)
  {
      printf("[Error] File %s does not exist, terminating..\n", config->file_name);
      errno = EBADF;
      return -1;
  }
  
  printf("[Info] Successful Connection Setup with [%s:%u], ready for file reception\n", 
      config->server_ip, ntohs(serv_addr.sin_port));
  return 0;

}
Exemplo n.º 22
0
int
main(int argc, char **argv)
{
    int					sockfd, len;
    char				*ptr, buf[2048], addrstr[INET_ADDRSTRLEN];
    struct ifconf		ifc;
    struct ifreq		*ifr;
    struct sockaddr_in	*sinptr;

    if ( (sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
        err_sys("socket error");

    ifc.ifc_len = sizeof(buf);
    ifc.ifc_req = (struct ifreq *) buf;
    if (ioctl(sockfd, SIOCGIFCONF, &ifc) < 0)
        err_sys("ioctl SIOCGIFCONF error");

    for (ptr = buf; ptr < buf + ifc.ifc_len; )
    {
        ifr = (struct ifreq *) ptr;
        len = sizeof(struct sockaddr);
#ifdef	HAVE_SOCKADDR_SA_LEN
        if (ifr->ifr_addr.sa_len > len)
            len = ifr->ifr_addr.sa_len;		/* length > 16 */
#endif
        ptr += sizeof(ifr->ifr_name) + len;	/* for next one in buffer */

        switch (ifr->ifr_addr.sa_family)
        {
        case AF_INET:
            sinptr = (struct sockaddr_in *) &ifr->ifr_addr;
            printf("%s\t%s\n", ifr->ifr_name,
                   Inet_ntop(AF_INET, &sinptr->sin_addr, addrstr, sizeof(addrstr)));
            break;

#ifdef	AF_INET6
        case AF_INET6:
        {
            struct sockaddr_in6	*sin6ptr;
            char addr6str[INET6_ADDRSTRLEN];

            sin6ptr = (struct sockaddr_in6 *) &ifr->ifr_addr;
            printf("%s\t%s\n", ifr->ifr_name,
                   Inet_ntop(AF_INET6, &sin6ptr->sin6_addr, addr6str, sizeof(addr6str)));
            break;
        }
#endif

#ifdef	HAVE_SOCKADDR_DL_STRUCT
        case AF_LINK:
        {
            struct sockaddr_dl	*sdlptr;
            char				str[18];
            char				*etherprint(const u_char *, char *);

            sdlptr = (struct sockaddr_dl *) &ifr->ifr_addr;
            printf("%s", ifr->ifr_name);
            if (sdlptr->sdl_index)
                printf("\t<link %d>", sdlptr->sdl_index);
            if (sdlptr->sdl_type == IFT_ETHER && sdlptr->sdl_alen)
                printf("\t%s", etherprint((u_char *) LLADDR(sdlptr), str));
            putchar('\n');
            break;
        }
#endif

        default:
            printf("%s\n", ifr->ifr_name);
            break;
        }
    }
    exit(0);
}
Exemplo n.º 23
0
int main(int argc, char ** argv){
	int  i, maxi, maxfd, listenfd, connfd, sockfd,val,nwritten;
	int  nready, client[NUMBEROFSTATIONS];
	ssize_t  n;
	fd_set   rset, allrset, wset,allwset;
	socklen_t    clilen;
	struct sockaddr_in    cliaddr, servaddr;
	int frame_number;
	int source_station_number;
	int destination_sockfd; //used to assign destination station socket number, 
	char *message1; //used to store first message
	char *message2; //used to store second message
	char source[INET_ADDRSTRLEN]; //used to the  third parameter of function inet_ntop
	char *sourceIP; //used to stored IP address of SP
	
	/* dest is an array that will store the destination station numbers
	and their corresponding socket descriptors. This will later be used to 
	send frame to destination station after receiving both messages of frame */	
	char *destinationIP; 
	char *destination_addr;
	int stored_destination_number;
	struct destination dest[NUMBEROFSTATIONS];
	/* initilize each station's sockfd to -1 */
	for (i = 0; i < NUMBEROFSTATIONS; i++){
		(dest + i)->destination_sockfd = -1;
	}
	
	struct frame * receiving_framePtr;
	struct cbp_storage  cbs;
	char col_mes[COLLISIONMESSAGE] = "Collision";
	char *collision_message = col_mes;

	listenfd = Socket(AF_INET, SOCK_STREAM, 0);
	bzero(&servaddr, sizeof(servaddr));
	servaddr.sin_family      = AF_INET;
	servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
	servaddr.sin_port        = htons(SERV_PORT);

	Bind(listenfd, (SA *) &servaddr, sizeof(servaddr));

	Listen(listenfd, LISTENQ);

	maxfd = listenfd;                       /* initialize */
	maxi = -1;                                      /* index into client[] array */
	
	/* Set to non-blocking mode using Fcntl for non-blocking IO*/
	
	/* Set socket descriptor that write to CBP output */
	val = Fcntl(fileno(stdout), F_GETFL, 0);
	Fcntl(fileno(stdout), F_SETFL, val | O_NONBLOCK);
	
	val = Fcntl(fileno(stdin), F_GETFL, 0);
	Fcntl(fileno(stdin), F_SETFL, val | O_NONBLOCK);
	for (i = 0; i < NUMBEROFSTATIONS; i++)
			client[i] = -1;                 /* -1 indicates available entry */
	FD_ZERO(&allrset);
	FD_ZERO(&allwset);
	FD_SET(listenfd, &allrset);
	
	maxfd = listenfd;
	
	int ctClient = 0;
	


    for ( ;; ) {
			
	rset = allrset; 
	//wset = allwset;/* structure assignment */
	nready = Select(maxfd+1, &rset, NULL, NULL, NULL);
	if (ctClient == NUMBEROFSTATIONS){			
		if (FD_ISSET(listenfd, &rset)) {        /* new client connection */
			clilen = sizeof(cliaddr);
			connfd = Accept(listenfd, (SA *) &cliaddr, &clilen);
			
			printf("New connection, sockfd: %d\n",connfd);	
			/* Save the just-connected station, e.i. its socket descriptor and its station number
			This information will later be used to send frame to destination station after
			receiving both message of frame */
			destinationIP = Inet_ntop(AF_INET, &cliaddr.sin_addr,source,INET_ADDRSTRLEN);
			stored_destination_number = ston(destinationIP);
			for (i = 0; i < NUMBEROFSTATIONS; i++){
				if((dest+i)->destination_sockfd < 0){
					(dest+i)->destination_sockfd = connfd;
					(dest+i)->destination_station_number = stored_destination_number;
					break;
				}
			}			
			/* Set socket descriptor to and from SP using Fcntl for non-blocking IO*/	
			val = Fcntl(connfd, F_GETFL, 0);
			Fcntl(connfd, F_SETFL, val | O_NONBLOCK);

			for (i = 0; i < NUMBEROFSTATIONS; i++)
				if (client[i] < 0) {
					client[i] = connfd; 
					ctClient++; 
					break;
				}
			FD_SET(connfd, &allrset);
			FD_SET(connfd, &allwset);

			if (connfd > maxfd)	
					maxfd = connfd;                
			if (i > maxi)
					maxi = i;                           

			if (--nready <= 0)
					continue;                          
	
		}       
		else //Clients full
		{
			break;
		}
	}
	}
	
	/*All Sps are now connect to the CBP, ready for sending frames*/	
	
	/*buffer_acquired is set to:   0 when first part of frame received																       1 when the second part of the frame sent, making the buffer ready for new frame 
					 or when a collision happens, discards the remaining part of the frame, allows stations to acquire the CBP storage
	*/
	char response;	
	printf("All stations are connected, ready to exchage data (Y/N):  \n");
        scanf("%*c %c",&response);
        if( (response == 'y') || (response == 'Y') ){	
	int buffer_acquired = 1;
	for( ; ; ){
	
		
		nready = Select(maxfd+1, &rset, &wset, NULL, NULL);

        for (i = 0; i <= maxi; i++) {   /* check all clients for data */
			sockfd = client[i];
			FD_SET(sockfd, &rset);
			sourceIP = Inet_ntop(AF_INET, &cliaddr.sin_addr,source,INET_ADDRSTRLEN);
			source_station_number = ston(sourceIP);
			
			if(buffer_acquired){	
				if(FD_ISSET(sockfd, &rset)){
					buffer_acquired = 0;
					if(n = Read(sockfd, receiving_framePtr,MAXLINE) == 0){
							Close(sockfd);
							FD_CLR(sockfd,&allrset);
							client[i] = -1;
					}
					else{
						/* Get information from struct frame type variable pointed by receiving_framePtr pointer
						that is received from SP */
						frame_number = receiving_framePtr->frame_number;						
						message1 = receiving_framePtr->message1;
						destination_addr = receiving_framePtr->destination_addr;
						int destination_station_number = ston(destination_addr);
						
						//inspect the message1					
						cbs.source_station_sd = sockfd;
						cbs.source_station_number = source_station_number;
						cbs.destination_station_number = destination_station_number;
						cbs.frame_number = frame_number;			
						strcpy(cbs.message1,message1);

						/*Turn on the bit to write to stdout*/
						FD_SET(fileno(stdout), &wset);
						if(FD_ISSET(fileno(stdout), &wset))
							fprintf(stdout,"Receive %s of frame %d from Station %d,to Station %d\n",
											message1,frame_number,source_station_number,destination_station_number);														
					}
					if (--nready <= 0)
						break;				/* no more readable descriptors */
				}
			}
			else{ 
				/* Buffer already store first message of a frame of a station
				Check if the receiving message is the second frame of that frame or
				the first message of a frame from another station */
				if (FD_ISSET(sockfd, &rset)){
					if(n = Read(sockfd, receiving_framePtr,MAXLINE) == 0){
						Close(sockfd);
						FD_CLR(sockfd,&allrset);
						client[i] = -1;
					}				
					else{/* Inspect the message if it is the second message 
							or the first message from another frame of another station*/
	
						/* Get information from struct frame type variable pointed by receiving_framePtr pointer
						that is received from SP */
						frame_number = receiving_framePtr->frame_number;			//get frame number				
						message2 = receiving_framePtr->message2;						//get the second message
						destination_addr = receiving_framePtr->destination_addr;	//get the destination address (string)
						int destination_station_number = ston(destination_addr);	//convert to number using ston function

						//Inspect the message
						//Check if the current source station number is the one whose first message has already been saved to CBP storage
						//If yes, save the second message
						if(cbs.source_station_number == source_station_number && 
									cbs.frame_number == frame_number){
							if(strcmp(message2,"part 2"==0)){
								strcpy(cbs.message2,message2);
							/*Turn on the bit to write to stdout*/
							FD_SET(fileno(stdout), &wset);
							if(FD_ISSET(fileno(stdout), &wset))
								fprintf(stdout,"Receive %s of frame %d from Station %d,to Station %d\n",
												message1,frame_number,source_station_number,destination_station_number);
								/* Turn on the bit in the wset to write to desination station the first message 
									Get the destination socket number from the dest array
								*/
								
								for( i = 0; i<NUMBEROFSTATIONS; i++){
									if((dest+i)->destination_station_number == cbs.destination_station_number)
										break;
								}
								destination_sockfd = (dest+i)->destination_sockfd;
								FD_SET(destination_sockfd, &wset);
							}
						}
						else{ /* Receiving frame from another station, inform both station a collision*/
						
							 /* Sending collision message to station that accquired the bus, discards the remaing parts of frame */						 
							buffer_acquired = 1;
							FD_SET(cbs.source_station_sd, &wset);		
							if(FD_ISSET(cbs.source_station_sd, &wset))
								Writen(cbs.source_station_sd, collision_message, strlen(COLLISIONMESSAGE));
								
							/*Sending collision message to another station*/
							if(FD_ISSET(sockfd, &wset))
								Writen(sockfd, collision_message, strlen(COLLISIONMESSAGE));
						}
					}
					if (--nready <= 0)
						break;				/* no more readable descriptors */
				}	
			}
			/* Sending the first message of the frame to destinaition SP*/

				
			} 
					

        }

    }




}
Exemplo n.º 24
0
void
if_init()
{
	struct hwa_info *hwa, *hwahead;
	struct sockaddr *sa;
	struct hostent *hptr;
	char *ptr;
	char **pptr;
	int i, j, prflag, n;
	struct arp_cache_entry cache_entry;

	memset(if_hwaddr, 0, sizeof(if_hwaddr));
	memset(if_sock, 0, sizeof(if_sock));
	if_size = 0;
	puts("<-- HW INFO -->");
	for (i = 0; i < NUM_VM; i++){
		sprintf(node_ip[i], "vm%d", i+1);
		hptr = gethostbyname(node_ip[i]);
		for (pptr = hptr->h_addr_list; *pptr != NULL; pptr++){
			Inet_ntop(hptr->h_addrtype, *pptr, node_ip[i], INET_ADDRSTRLEN);
		}
	}
	for (hwahead = hwa = Get_hw_addrs(); hwa != NULL; hwa = hwa->hwa_next) {
		printf("interface index = %d\n", (n = hwa->if_index));
		printf("%s :%s", hwa->if_name,
				((hwa->ip_alias) == IP_ALIAS) ? " (alias)\n" : "\n");

		if ((hwa->ip_alias) != IP_ALIAS) {
			if_size++;
		}
		if ((sa = hwa->ip_addr) != NULL) {
			printf("\tIP addr = %s\n", Sock_ntop_host(sa, sizeof(*sa)));

			if (hwa->if_haddr != NULL) {
				if (strcmp(hwa->if_haddr, if_hwaddr[my_index])
						== 0 && (hwa->ip_alias) == IP_ALIAS) {
					insert_local_hw_cache(Sock_ntop_host(sa, sizeof(*sa)));
				}
			}
		}
		// get canonical ip
		if (strcmp(hwa->if_name, "eth0") == 0) {
			sprintf(my_ip, "%s", Sock_ntop_host(sa, sizeof(*sa)));

			my_index = hwa->if_index;
			for (my_vm = 0; my_vm < NUM_VM; my_vm++) {
				if (strcmp(my_ip, node_ip[my_vm]) == 0) {
					my_vm++;
					break;
				}
			}
		}

		prflag = i = 0;
		do {
			if (hwa->if_haddr[i] != '\0') {
				prflag = 1;
				break;
			}
		} while (++i < IF_HADDR);

		if (prflag) {
			printf("\tHW addr = ");
			for (i = 0; i < IF_HADDR; i++) {
				if_hwaddr[n][i] = hwa->if_haddr[i];
				printf("%02x ", (int) if_hwaddr[n][i] & 0xff);
			}
			puts("");
		}
	}
	// printf("***info: number of interfaces -- %d\n***", if_size);
	// Create PF_PACKET socket for etho0
	if_sockfd = Socket(AF_PACKET, SOCK_RAW, htons(ARP_PROTOCOL));

	addr.sll_family = PF_PACKET;
	addr.sll_protocol = htons(ARP_PROTOCOL);
	addr.sll_ifindex = my_index;
	addr.sll_hatype = ARPHRD_ETHER;
	addr.sll_pkttype = PACKET_HOST;
	addr.sll_halen = ETH_ALEN;

	for (j = 0; j < ETH_ALEN; j++){
		addr.sll_addr[j] = if_hwaddr[my_index][j];
	}

	Bind(if_sockfd, (SA *)&addr, sizeof(struct sockaddr_ll));
	maxfd= (maxfd, if_sockfd);
	insert_local_hw_cache(my_ip);
	// puts("if_init done\n");
	puts("");
}
Exemplo n.º 25
0
int
main(int argc, char **argv)
{
	int					i, maxi, maxfd, listenfd, connfd, sockfd;
	int					nready, client[FD_SETSIZE];
	ssize_t				n;
	fd_set				rset, allset;
	char				line[MAXLINE];
	socklen_t			clilen;
	struct sockaddr_in	cliaddr, servaddr;

	listenfd = Socket(AF_INET, SOCK_STREAM, 0);

	bzero(&servaddr, sizeof(servaddr));
	servaddr.sin_family      = AF_INET;
	servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
	servaddr.sin_port        = htons(7);

	Bind(listenfd, (SA *) &servaddr, sizeof(servaddr));

	Listen(listenfd, LISTENQ);

	maxfd = listenfd;			/* initialize */
	maxi = -1;					/* index into client[] array */
	for (i = 0; i < FD_SETSIZE; i++)
		client[i] = -1;			/* -1 indicates available entry */
	FD_ZERO(&allset);
	FD_SET(listenfd, &allset);

	for ( ; ; ) {
		rset = allset;
		nready = Select(maxfd+1, &rset, NULL, NULL, NULL);

		if (FD_ISSET(listenfd, &rset)) {	/* new client connection */
			printf("listening socket readable\n");
			sleep(5);
			clilen = sizeof(cliaddr);
			connfd = Accept(listenfd, (SA *) &cliaddr, &clilen);
#ifdef	NOTDEF
			printf("new client: %s, port %d\n",
					Inet_ntop(AF_INET, &cliaddr.sin_addr, 4, NULL),
					ntohs(cliaddr.sin_port));
#endif

			for (i = 0; i < FD_SETSIZE; i++)
				if (client[i] < 0) {
					client[i] = connfd;	/* save descriptor */
					break;
				}
			if (i == FD_SETSIZE)
				err_quit("too many clients");

			FD_SET(connfd, &allset);	/* add new descriptor to set */
			if (connfd > maxfd)
				maxfd = connfd;			/* for select */
			if (i > maxi)
				maxi = i;				/* max index in client[] array */

			if (--nready <= 0)
				continue;				/* no more readable descriptors */
		}

		for (i = 0; i <= maxi; i++) {	/* check all clients for data */
			if ( (sockfd = client[i]) < 0)
				continue;
			if (FD_ISSET(sockfd, &rset)) {
				if ( (n = Readline(sockfd, line, MAXLINE)) == 0) {
						 /* connection closed by client */
					Close(sockfd);
					FD_CLR(sockfd, &allset);
					client[i] = -1;
				}
				Writen(sockfd, line, n);

				if (--nready <= 0)
					break;				/* no more readable descriptors */
			}
		}
	}
}
Exemplo n.º 26
0
int
readable_v4(void)
{
    int					i, hlen1, hlen2, icmplen, sport;
    char				buf[MAXLINE];
    char				srcstr[INET_ADDRSTRLEN], dststr[INET_ADDRSTRLEN];
    ssize_t				n;
    socklen_t			len;
    struct ip			*ip, *hip;
    struct icmp			*icmp;
    struct udphdr		*udp;
    struct sockaddr_in	from, dest;
    struct icmpd_err	icmpd_err;

    len = sizeof(from);
    n = Recvfrom(fd4, buf, MAXLINE, 0, (SA *) &from, &len);

    printf("%d bytes ICMPv4 from %s:",
           n, Sock_ntop_host((SA *) &from, len));

    ip = (struct ip *) buf;		/* start of IP header */
    hlen1 = ip->ip_hl << 2;		/* length of IP header */

    icmp = (struct icmp *) (buf + hlen1);	/* start of ICMP header */
    if ( (icmplen = n - hlen1) < 8)
        err_quit("icmplen (%d) < 8", icmplen);

    printf(" type = %d, code = %d\n", icmp->icmp_type, icmp->icmp_code);
    /* end readable_v41 */

    /* include readable_v42 */
    if (icmp->icmp_type == ICMP_UNREACH ||
            icmp->icmp_type == ICMP_TIMXCEED ||
            icmp->icmp_type == ICMP_SOURCEQUENCH)
    {
        if (icmplen < 8 + 20 + 8)
            err_quit("icmplen (%d) < 8 + 20 + 8", icmplen);

        hip = (struct ip *) (buf + hlen1 + 8);
        hlen2 = hip->ip_hl << 2;
        printf("\tsrcip = %s, dstip = %s, proto = %d\n",
               Inet_ntop(AF_INET, &hip->ip_src, srcstr, sizeof(srcstr)),
               Inet_ntop(AF_INET, &hip->ip_dst, dststr, sizeof(dststr)),
               hip->ip_p);
        if (hip->ip_p == IPPROTO_UDP)
        {
            udp = (struct udphdr *) (buf + hlen1 + 8 + hlen2);
            sport = udp->uh_sport;

            /* 4find client's Unix domain socket, send headers */
            for (i = 0; i <= maxi; i++)
            {
                if (client[i].connfd >= 0 &&
                        client[i].family == AF_INET &&
                        client[i].lport == sport)
                {

                    bzero(&dest, sizeof(dest));
                    dest.sin_family = AF_INET;
#ifdef	HAVE_SOCKADDR_SA_LEN
                    dest.sin_len = sizeof(dest);
#endif
                    memcpy(&dest.sin_addr, &hip->ip_dst,
                           sizeof(struct in_addr));
                    dest.sin_port = udp->uh_dport;

                    icmpd_err.icmpd_type = icmp->icmp_type;
                    icmpd_err.icmpd_code = icmp->icmp_code;
                    icmpd_err.icmpd_len = sizeof(struct sockaddr_in);
                    memcpy(&icmpd_err.icmpd_dest, &dest, sizeof(dest));

                    /* 4convert type & code to reasonable errno value */
                    icmpd_err.icmpd_errno = EHOSTUNREACH;	/* default */
                    if (icmp->icmp_type == ICMP_UNREACH)
                    {
                        if (icmp->icmp_code == ICMP_UNREACH_PORT)
                            icmpd_err.icmpd_errno = ECONNREFUSED;
                        else if (icmp->icmp_code == ICMP_UNREACH_NEEDFRAG)
                            icmpd_err.icmpd_errno = EMSGSIZE;
                    }
                    Write(client[i].connfd, &icmpd_err, sizeof(icmpd_err));
                }
            }
        }
    }
    return(--nready);
}
Exemplo n.º 27
0
void main() {

    struct hw_ip_pair *hi_pair;
    char IP_str[20], cache_hw_addr[6];
    fd_set rset;
    int cache_ifindex, cache_hatype;
    struct hw_addr HWaddr;

    hi_pair = malloc(sizeof(struct hw_ip_pair));
    get_hw_ip_pair(hi_pair);

    printf("My IP :%s,\t HW addr", hi_pair->ip_addr);
    print_mac_to_string(hi_pair->hw_addr);
    printf("\n");

    int pf_pack_sockfd = create_pf_pack_socket();
    void* buffer = (void*)malloc(ETH_FRAME_LEN);

    int listen_sockfd, conn_sockfd, clilen, n;
    struct sockaddr_un servaddr, cliaddr;
    char sendline[MAXLINE], recvline[MAXLINE];
    struct sockaddr_in *destIP = malloc(sizeof(struct sockaddr_in));
    char ip_addr[20];
    struct arp_packet *arp_req = malloc(sizeof(struct arp_packet));
    struct arp_packet *arp_rep = malloc(sizeof(struct arp_packet));
    struct arp_packet *arp_recv = malloc(sizeof(struct arp_packet));
    struct sockaddr_ll socket_address; 
    int ll_len = sizeof(struct sockaddr_ll);
    int i=0;

    listen_sockfd = Socket(AF_LOCAL, SOCK_STREAM, 0);
    unlink(SUN_PATH_ARP);
    bzero(&servaddr, sizeof(servaddr));
    servaddr.sun_family = AF_LOCAL;
    strcpy(servaddr.sun_path, SUN_PATH_ARP);
    Bind(listen_sockfd, (SA *) &servaddr, sizeof(servaddr));
    Listen(listen_sockfd, LISTENQ);

    int lookup_flag=0;
    clilen = sizeof(struct sockaddr_un);
    while(1) {

        FD_ZERO(&rset);

        FD_SET(listen_sockfd, &rset);
        FD_SET(pf_pack_sockfd, &rset);
        FD_SET(conn_sockfd, &rset);
        int max;

        if(conn_sockfd != 0)
            max = max(max(listen_sockfd, conn_sockfd),pf_pack_sockfd);
        else	
            max = max(listen_sockfd,pf_pack_sockfd);
        int ret = select(max+1, &rset, NULL, NULL, NULL);

        if(FD_ISSET(listen_sockfd, &rset)) {
            conn_sockfd = Accept(listen_sockfd, (SA *) &cliaddr, &clilen);
            /*			n = read(conn_sockfd, destIP, sizeof(struct sockaddr_in));
                        Inet_ntop(AF_INET, &(destIP->sin_addr), ip_addr, 20);

            // Lookup for the <HW,IP> pair in the ARP cache
            lookup_arp_cache(ip_addr, cache_hw_addr, &cache_ifindex, &cache_hatype,&lookup_flag);


            if(lookup_flag == 0) {
            printf("Entry not found from cache\n");
            create_arp_request_packet(arp_req, ip_addr, hi_pair);
            send_arp_request(pf_pack_sockfd, arp_req, hi_pair, conn_sockfd);
            }
            else{
            printf("Entry found from cache\n");
            // Send from cache
            HWaddr.sll_ifindex = cache_ifindex;
            HWaddr.sll_hatype = cache_hatype;
            HWaddr.sll_halen = sizeof(cache_hatype);

            memcpy(HWaddr.mac_addr, cache_hw_addr,6); 

            print_mac_to_string(HWaddr.mac_addr);
            Write(conn_sockfd, (void *)&HWaddr, sizeof(HWaddr));
            close(conn_sockfd);

            }
            printf("Sent ARP request\n");
             */		}

        else if(ret!= -1 && FD_ISSET(conn_sockfd, &rset)) {
            n = read(conn_sockfd, destIP, sizeof(struct sockaddr_in));
            Inet_ntop(AF_INET, &(destIP->sin_addr), ip_addr, 20);

            // Lookup for the <HW,IP> pair in the ARP cache
            lookup_arp_cache(ip_addr, cache_hw_addr, &cache_ifindex, &cache_hatype,&lookup_flag);


            if(lookup_flag == 0) {
                create_arp_request_packet(arp_req, ip_addr, hi_pair);
                printf("send 1\n");
                send_arp_request(pf_pack_sockfd, arp_req, hi_pair, conn_sockfd);
            }   
            else{
                // Send from cache
                HWaddr.sll_ifindex = cache_ifindex;
                HWaddr.sll_hatype = cache_hatype;
                HWaddr.sll_halen = sizeof(cache_hatype);

                memcpy(HWaddr.mac_addr, cache_hw_addr,6);

                //				print_mac_to_string(HWaddr.mac_addr);
                Write(conn_sockfd, (void *)&HWaddr, sizeof(HWaddr));
                close(conn_sockfd);
                conn_sockfd = 0;
            }
        }

        else if(FD_ISSET(pf_pack_sockfd, &rset)) {

            Recvfrom(pf_pack_sockfd, buffer, ETH_FRAME_LEN, 0, (SA *)&socket_address, &ll_len);
            void *data = buffer + 14;
            arp_rep = (struct arp_packet *)data;
            if (arp_rep->id == ARP_ID){
                if(arp_rep->op == ARP_REQ) {
                    if(strcmp(arp_rep->dest_IP, hi_pair->ip_addr) == 0) {

                        printf("Printing Ethernet Header and ARP Request Packet Received\n");
                        print_ethernet_and_arp(arp_rep->src_mac, arp_rep->dest_mac, arp_rep);
                        add_to_arp_cache_list(arp_rep->src_IP, arp_rep->src_mac, socket_address.sll_ifindex, socket_address.sll_hatype, conn_sockfd, 1);
                        //						print_arp_cache_list();
                        create_arp_reply_packet(arp_recv, arp_rep->src_IP, hi_pair, arp_rep->src_mac, arp_rep->id);
                        send_arp_reply(pf_pack_sockfd, arp_recv, hi_pair, socket_address.sll_ifindex);
                    }
                    else {
                        update_arp_cache(arp_rep->src_IP, arp_rep->src_mac, socket_address.sll_ifindex, 0, conn_sockfd);
                    }
                    continue;
                }
                else if(arp_rep->op == ARP_REP) {
                    if(ret == -1) {
                        delete_from_arp_cache(arp_rep->src_IP);
                        //						print_arp_cache_list();
                        continue;
                    }

                    printf("Printing Ethernet Header and ARP Reply Packet Received\n");
                    print_ethernet_and_arp(arp_rep->src_mac, arp_rep->dest_mac, arp_rep);

                    update_arp_cache(arp_rep->src_IP, arp_rep->src_mac, socket_address.sll_ifindex, 0, conn_sockfd);
                    //					print_arp_cache_list();
                    HWaddr.sll_ifindex = socket_address.sll_ifindex;
                    HWaddr.sll_hatype = socket_address.sll_hatype;
                    HWaddr.sll_halen = socket_address.sll_halen;

                    memcpy(HWaddr.mac_addr, arp_rep->src_mac,6); 

                    //					print_mac_to_string(HWaddr.mac_addr);
                    Write(conn_sockfd, (void *)&HWaddr, sizeof(HWaddr));
                    close(conn_sockfd);
                    conn_sockfd = 0;
                    update_arp_cache(arp_rep->src_IP, arp_rep->src_mac, socket_address.sll_ifindex, 0, -1);
                    //					print_arp_cache_list();
                }
            }

        }
    }
}
Exemplo n.º 28
0
int main(int argc, char argv**)
{
	socklen_t len;
	int n, listenfd, connfd, char_in, count = 0;
	struct sockaddr_in  servaddr, cliaddr;
	char buff[40], wbuff[MAXLINE], rbuff[MAXLINE], cmd[16], path1[64]=".", path[64], vers[16];

	FILE * hFile;

	if(argc != 2)
	{
		err_quit("usage: a.out <Port>");
	}

	listenfd = Socket(AF_INET, SOCK_STREAM, 0);

	bzero(&servaddr, sizeof(servaddr));
	servaddr.sin_family = AF_INET;
	servaddr.sin_addr.sin_addr = htonl(INADDR_ANY);
	servaddr.sin_port = htons(atoi(argv[1]));

	Bind(listenfd, (SA*) &servaddr, sizeof(servaddr));

	Listen(listenfd, LISTENQ);

	for( ; ; )
	{
		len = sizeof(cliaddr);

		connfd  = Accept(listenfd, (SA*) &cliaddr, &len);
		printf("\nConnection from %s, port %d\n", Inet_ntop(AF_INET, &cliaddr.sin_addr, buff, sizeof(buff)) ntohs(cliaddr.sin_port));

		while((n = read(connfd, rbuff, MAXLINE)) > 0)
		{
			rbuff[n] = 0;

			if(fputs(rbuff, stdout) == 0)
			{
				err_sys("fputs error");
			}

			if(strstr(rbuff,"\r\n\r\n") > 0)
			{
				break;
			}
		}

		if(n < 0)
		{
			err_sys("read error");
		}

		sscanf(rbuff, "%s %s %s", cmd, path, vers);
		strcat(path1, path);
		if(strcmp(path1, "./") == 0)
		{
			strcpy(path1, "./index.html");
		}

		hFile = fopen(path1, "r");
		if(hFile == NULL)
		{
			hFIle = fopen("error.html", "r");
		}

		strcpy(wbuff,"");

		while((char_in = fgetc(hFile)) != EOF)
		{
			wbuff(count) = char_in;
			count++;
		}

		wbuff(count) = 0;

		Write(connfd, wbuff, strlen(wbuff));

		count = 0;
		fclose(hFile);
		strcpy(path1,".");

		Close(connfd);
	}
}