コード例 #1
0
ファイル: broadcast.c プロジェクト: dslab-epfl/dimmunix
int main(int argc, char **argv)
{
    NLsocket    sock;
    NLaddress   addr, *alladdr;
    NLbyte      string[NL_MAX_STRING_LENGTH];
    NLenum      type = NL_IP; /* default network type */
    NLint       count;

    if(nlInit() == NL_FALSE)
        printErrorExit();

    printf("nlGetString(NL_VERSION) = %s\n\n", nlGetString(NL_VERSION));
    printf("nlGetString(NL_NETWORK_TYPES) = %s\n\n", nlGetString(NL_NETWORK_TYPES));

    if (argc == 2)
    {
        if(strcmp(argv[1], "NL_IPX") == 0)
        {
            type = NL_IPX;
        }
        else if(strcmp(argv[1], "NL_LOOP_BACK") == 0)
        {
            type = NL_LOOP_BACK;
        }
    }

    if(nlSelectNetwork(type) == NL_FALSE)
        printErrorExit();

    /* list all the local addresses */
    printf("local addresses are:\n");
    alladdr = nlGetAllLocalAddr(&count);
    while(count-- > 0)
    {
        printf("  %s\n", nlAddrToString(alladdr++, string));
    }
    printf("\n");
    nlEnable(NL_SOCKET_STATS);
    /* enable reuse address to run two or more copies on one machine */
    nlHint(NL_REUSE_ADDRESS, NL_TRUE);

    /* create a client socket */
    sock = nlOpen(25000, NL_BROADCAST);

    if(sock == NL_INVALID)
        printErrorExit();

    nlGetLocalAddr(sock, &addr);
    printf("socket address is %s\n", nlAddrToString(&addr, string));
    mainTestLoop(sock);

    nlShutdown();
    return 0;
}
コード例 #2
0
ファイル: eqtest.c プロジェクト: tsky1971/hawknl
int main(int argc, char **argv)
{
    NLsocket    sock;
    NLaddress   addr;
    NLbyte      server[] = "status.everquest.com";
    NLushort    port = 24252;
    NLbyte      command[] = {0xFF, 0xFF, 0x09, 0x00};
    NLenum      type = NL_UNRELIABLE; /* UDP */
    NLbyte      buffer[1024];
    NLint       count;

    if(!nlInit())
       return 1;
    if(!nlSelectNetwork(NL_IP))
    {
        nlShutdown();
        return 1;
    }
    nlEnable(NL_BLOCKING_IO);
    /* create server the address */
    nlGetAddrFromName(server, &addr);
    nlSetAddrPort(&addr, port);
    /* create the socket */
    sock = nlOpen(0, type);
    if(sock == NL_INVALID)
    {
        nlShutdown();
        return 1;
    }
    /* set the destination address */
    nlSetRemoteAddr(sock, &addr);
    /* send the message */
    nlWrite(sock, (NLvoid *)command, (NLint)sizeof(NLulong));
    /* read the reply */
    count = nlRead(sock, (NLvoid *)buffer, (NLint)sizeof(buffer));
    if(count > 0)
    {
        printf("Banner is: %s\n", &buffer[4]);
    }
    nlShutdown();
    return 0;
}
コード例 #3
0
ファイル: Networking.cpp プロジェクト: iamnilay3/openlierox
bool NetworkSocket::OpenBroadcast(Port port) {
	if(isOpen()) {
		warnings << "NetworkSocket " << debugString() << ": OpenBroadcast: socket is already opened, reopening now" << endl;
		Close();
	}

	NLsocket ret = nlOpen(port, NL_BROADCAST);
	if (ret == NL_INVALID)  {
#ifdef DEBUG
		errors << "OpenBroadcastSocket: " << GetLastErrorStr() << endl;
#endif
		ResetSocketError();
		return false;
	}
	m_socket->sock = ret;
	m_type = NST_UDPBROADCAST;
	m_state = NSS_NONE;
	checkEventHandling();
	return true;	
}
コード例 #4
0
ファイル: getfile.c プロジェクト: tsky1971/hawknl
int main(int argc, char **argv)
{
    NLsocket    sock;
    NLaddress   addr;
    NLbyte      buffer[4096];
    int         f;
    NLint       count, total = 0;
    NLint       crfound = 0;
    NLint       lffound = 0;

    if (argc != 4)
    {
        printf("\nSyntax: getfile ServerName FullPath LocalFile\n");
        return 1;
    }

    if(nlInit() == NL_FALSE)
        printErrorExit();

    if(nlSelectNetwork(NL_IP) == NL_FALSE)
        printErrorExit();

    nlEnable(NL_SOCKET_STATS);
    nlEnable(NL_BLOCKING_IO);

    nlGetAddrFromName(argv[1], &addr);

    /* use the standard HTTP port */
    nlSetAddrPort(&addr, 80);
    printf("Server address is %s\n\n", nlAddrToString(&addr, buffer));

    /* open the socket and connect to the server */
    sock = nlOpen(0, NL_TCP);
    if(sock == NL_INVALID)
        printErrorExit();
    if(nlConnect(sock, &addr) == NL_FALSE)
    {
        printErrorExit();
    }

    printf("Connected\n");
    /* open the local file */
    f = open(argv[3], O_BINARY|O_CREAT|O_TRUNC|O_RDWR, S_IWRITE | S_IREAD);
    if(f < 0)
    {
        printf("Could not open local file\n");
        printErrorExit();
    }

    /* now let's ask for the file */
#ifdef TEST_GZIP
    /* this is for my own personal use to test compressed web pages */
    sprintf(buffer, "GET %s HTTP/1.1\r\nHost:%s\r\nAccept: */*\r\nAccept-Encoding: gzip\r\nUser-Agent: HawkNL sample program Getfile\r\n\r\n"
                    , argv[2], argv[1]);
#else
    sprintf(buffer, "GET %s HTTP/1.0\r\nHost:%s\r\nAccept: */*\r\nUser-Agent: HawkNL sample program Getfile\r\n\r\n"
                    , argv[2], argv[1]);
#endif
    if(nlWrite(sock, (NLvoid *)buffer, (NLint)strlen(buffer)) == NL_INVALID)
    {
        close(f);
        printErrorExit();
    }

    /* receive the file and write it locally */
    while(1 == 1)
    {
        count = nlRead(sock, (NLvoid *)buffer, (NLint)sizeof(buffer) - 1);
        if(count < 0)
        {
            NLint err = nlGetError();

            /* is the connection closed? */
            if(err == NL_MESSAGE_END)
            {
                break;
            }
            else
            {
                close(f);
                printErrorExit();
            }
        }
        total += count;
        if(count > 0)
        {
            /* parse out the HTTP header */
            if(lffound < 2)
            {
                int i;
                
                for(i=0;i<count;i++)
                {
                    if(buffer[i] == 0x0D)
                    {
                        crfound++;
                    }
                    else
                    {
                        if(buffer[i] == 0x0A)
                        {
                            lffound++;
                        }
                        else
                        {
                            /* reset the CR and LF counters back to 0 */
                            crfound = lffound = 0;
                        }
                    }
                    if(lffound == 2)
                    {
                        /* i points to the second LF */
                        /* NUL terminate the header string and print it out */
                        buffer[i] = buffer[i-1] = 0x0;
                        printf(buffer);

                        /* write out the rest to the file */
                        write(f, &buffer[i+1], count - i - 1);

                        break;
                    }
                }
                if(lffound < 2)
                {
                    /* we reached the end of buffer, so print it out */
                    buffer[count + 1] = 0x0;
                    printf(buffer);
                }
            }
            else
            {
                write(f, buffer, count);
                printf("received %d bytes at %d bytes per second\r",
                    total, nlGetSocketStat(sock, NL_AVE_BYTES_RECEIVED));
            }
        }
    }

    close(f);
    nlShutdown();
    return 0;
}
コード例 #5
0
ファイル: test.c プロジェクト: tsky1971/hawknl
int main(int argc, char **argv)
{
    NLboolean   isserver = NL_FALSE;
    NLsocket    serversock;
    NLsocket    clientsock;
    NLaddress   addr;
    NLbyte      server[] = "127.0.0.1:25000";
    NLenum      type = NL_UNRELIABLE; /* Change this to NL_RELIABLE for reliable connection */
    NLbyte      string[NL_MAX_STRING_LENGTH];

    if(!nlInit())
        printErrorExit();

    printf("nlGetString(NL_VERSION) = %s\n\n", nlGetString(NL_VERSION));
    printf("nlGetString(NL_NETWORK_TYPES) = %s\n\n", nlGetString(NL_NETWORK_TYPES));

    if(!nlSelectNetwork(NL_IP))
        printErrorExit();

    if(argc > 1)
    {
        if(!strcmp(argv[1], "-s")) /* server mode */
            isserver = NL_TRUE;
    }

    if(isserver)
    {
        /* create a server socket */
        serversock = nlOpen(25000, type); /* just a random port number ;) */

        if(serversock == NL_INVALID)
            printErrorExit();

        if(!nlListen(serversock))       /* let's listen on this socket */
        {
            nlClose(serversock);
            printErrorExit();
        }
        nlGetLocalAddr(serversock, &addr);
        printf("Server address is %s\n", nlAddrToString(&addr, string));
        mainServerLoop(serversock);
    }
    else
    {
        /* create a client socket */
        clientsock = nlOpen(0, type); /* let the system assign the port number */
        nlGetLocalAddr(clientsock, &addr);
        printf("our address is %s\n", nlAddrToString(&addr, string));

        if(clientsock == NL_INVALID)
            printErrorExit();
        /* create the NLaddress */
        nlStringToAddr(server, &addr);
        printf("Address is %s\n", nlAddrToString(&addr, string));
        /* now connect */
        if(!nlConnect(clientsock, &addr))
        {
            nlClose(clientsock);
            printErrorExit();
        }
        mainClientLoop(clientsock);
    }

    nlShutdown();
    return 0;
}
コード例 #6
0
ファイル: macvtap.c プロジェクト: hjwsm1989/libvirt
/**
 * nlComm:
 * @nlmsg: pointer to netlink message
 * @respbuf: pointer to pointer where response buffer will be allocated
 * @respbuflen: pointer to integer holding the size of the response buffer
 *      on return of the function.
 * @nl_pid: the pid of the process to talk to, i.e., pid = 0 for kernel
 *
 * Send the given message to the netlink layer and receive response.
 * Returns 0 on success, -1 on error. In case of error, no response
 * buffer will be returned.
 */
static
int nlComm(struct nlmsghdr *nlmsg,
           char **respbuf, unsigned int *respbuflen,
           int nl_pid)
{
    int rc = 0;
    struct sockaddr_nl nladdr = {
            .nl_family = AF_NETLINK,
            .nl_pid    = nl_pid,
            .nl_groups = 0,
    };
    int rcvChunkSize = 1024; // expecting less than that
    int rcvoffset = 0;
    ssize_t nbytes;
    struct timeval tv = {
        .tv_sec = NETLINK_ACK_TIMEOUT_S,
    };
    fd_set readfds;
    int fd = nlOpen();
    int n;

    if (fd < 0)
        return -1;

    nlmsg->nlmsg_pid = getpid();
    nlmsg->nlmsg_flags |= NLM_F_ACK;

    nbytes = sendto(fd, (void *)nlmsg, nlmsg->nlmsg_len, 0,
                    (struct sockaddr *)&nladdr, sizeof(nladdr));
    if (nbytes < 0) {
        virReportSystemError(errno,
                             "%s", _("cannot send to netlink socket"));
        rc = -1;
        goto err_exit;
    }

    FD_ZERO(&readfds);
    FD_SET(fd, &readfds);

    n = select(fd + 1, &readfds, NULL, NULL, &tv);
    if (n <= 0) {
        if (n < 0)
            virReportSystemError(errno, "%s",
                                 _("error in select call"));
        if (n == 0)
            virReportSystemError(ETIMEDOUT, "%s",
                                 _("no valid netlink response was received"));
        rc = -1;
        goto err_exit;
    }

    while (1) {
        if (VIR_REALLOC_N(*respbuf, rcvoffset+rcvChunkSize) < 0) {
            virReportOOMError();
            rc = -1;
            goto err_exit;
        }

        socklen_t addrlen = sizeof(nladdr);
        nbytes = recvfrom(fd, &((*respbuf)[rcvoffset]), rcvChunkSize, 0,
                          (struct sockaddr *)&nladdr, &addrlen);
        if (nbytes < 0) {
            if (errno == EAGAIN || errno == EINTR)
                continue;
            virReportSystemError(errno, "%s",
                                 _("error receiving from netlink socket"));
            rc = -1;
            goto err_exit;
        }
        rcvoffset += nbytes;
        break;
    }
    *respbuflen = rcvoffset;

err_exit:
    if (rc == -1) {
        VIR_FREE(*respbuf);
        *respbuf = NULL;
        *respbuflen = 0;
    }

    nlClose(fd);
    return rc;
}


static struct rtattr *
rtattrCreate(char *buffer, int bufsize, int type,
             const void *data, int datalen)
{
    struct rtattr *r = (struct rtattr *)buffer;
    r->rta_type = type;
    r->rta_len  = RTA_LENGTH(datalen);
    if (r->rta_len > bufsize)
        return NULL;
    memcpy(RTA_DATA(r), data, datalen);
    return r;
}


static void
nlInit(struct nlmsghdr *nlm, int flags, int type)
{
    nlm->nlmsg_len = NLMSG_LENGTH(0);
    nlm->nlmsg_flags = flags;
    nlm->nlmsg_type = type;
}
コード例 #7
0
ファイル: tracker.cpp プロジェクト: yixu34/Mastrix
/*
 * This code based on the 'getfile' sample program for the HawkNL
 * network library, which is
 * Copyright (C) 2000-2002 Phil Frisbie, Jr. ([email protected])
 */
void *httpGet(void *a)
{
	HttpConnection *opt = (HttpConnection*)a;
	NLsocket    sock;
	NLaddress   addr;
	NLbyte      buffer[4096];
	NLint       count, total = 0;
	NLint       crfound = 0;
	NLint       lffound = 0;

	nlGetAddrFromName(opt->serverName.c_str(), &addr);

	/* use the standard HTTP port */
	nlSetAddrPort(&addr, 80);

	/* open the socket and connect to the server */
	sock = nlOpen(0, NL_TCP);
	if(sock == NL_INVALID)
	{
		opt->success = false;
		opt->finished = true;
		opt->error = getNlError();
		return 0;
	}
	if(nlConnect(sock, &addr) == NL_FALSE)
	{
		opt->success = false;
		opt->finished = true;
		opt->error = getNlError();
		return 0;
	}

	/* now let's ask for the file */
	sprintf(buffer, "GET %s HTTP/1.0\r\nHost:%s\r\nAccept: */*\r\nUser-Agent: HawkNL sample program Getfile\r\n\r\n"
	              , opt->path.c_str(), opt->serverName.c_str());
	while(1)
	{
		int ret = nlWrite(sock, (NLvoid *)buffer, (NLint)strlen(buffer));
		if(ret != NL_INVALID)
			break;
		if(nlGetError() == NL_CON_PENDING)
			htThreadSleep(30);
		else
		{
			opt->success = false;
			opt->finished = true;
			opt->error = getNlError();
			return 0;
		}
	}

	/* receive the file and write it locally */
	while(1)
	{
		count = nlRead(sock, (NLvoid *)buffer, (NLint)sizeof(buffer) - 1);
		if(count < 0)
		{
			NLint err = nlGetError();

			/* is the connection closed? */
			if(err == NL_MESSAGE_END)
				break;
			else
			{
				opt->success = false;
				opt->finished = true;
				opt->error = getNlError();
				return 0;
			}
		}
		total += count;
		if(count > 0)
		{
			/* parse out the HTTP header */
			if(lffound < 2)
			{
				int i;
	            
				for(i=0;i<count;i++)
				{
					if(buffer[i] == 0x0D)
						crfound++;
					else
					{
						if(buffer[i] == 0x0A)
							lffound++;
						else
							crfound = lffound = 0; /* reset the CR and LF counters back to 0 */
					}
					if(lffound == 2)
					{
						/* i points to the second LF */
						/* NUL terminate the header string and print it out */
						buffer[i] = buffer[i-1] = 0x0;

						/* write out the rest to the file */
						int writesize = count-i-1;
						char *writestart = &buffer[i+1];
						
						opt->mutex.lock();
							while(opt->len+writesize >= opt->alloc) {
								opt->alloc *= 2;
								opt->data = (char*)realloc(opt->data, opt->alloc);
								memset(opt->data+opt->len, 0, opt->alloc-opt->len);
							}
							memcpy(opt->data+opt->len, writestart, writesize);
							opt->len += writesize;
						opt->mutex.unlock();

						break;
					}
				}
				if(lffound < 2)
					buffer[count + 1] = 0x0; /* we reached the end of buffer */
			} else {
				opt->mutex.lock();
					while(opt->len+count >= opt->alloc) {
						opt->alloc *= 2;
						opt->data = (char*)realloc(opt->data, opt->alloc);
						memset(opt->data+opt->len, 0, opt->alloc-opt->len);
					}
					memcpy(opt->data+opt->len, buffer, count);
					opt->len += count;
				opt->mutex.unlock();
			}
		}
		htThreadSleep(15);
	}
	opt->success = true;
	opt->finished = true;
	return 0;
}