Exemplo n.º 1
0
void Url::getHostWithPort(UtlString& domain) const
{
   getHostAddress(domain);
   if (mHostPort != PORT_NONE)
   {
      char portNum[7];
      sprintf(portNum, ":%d", mHostPort);
      domain.append(portNum);
   }
}
Exemplo n.º 2
0
void Url::dump()
{
    UtlString proto;
    getUrlType(proto);
    printf("Url type: '%s'\n", proto.data());

    UtlString disp;
    getDisplayName(disp);
    printf("DisplayName: '%s'\n", disp.data());

    UtlString user;
    getUserId(user);
    printf("UserId: '%s'\n", user.data());

    UtlString pwd;
    getPassword(pwd);
    printf("Password: '******'\n", pwd.data());

    UtlString server;
    getHostAddress(server);
    printf("Address: '%s'\n", server.data());

    int port = getHostPort();
    printf("Port: %d\n", port);

    UtlString callId;
    getHeaderParameter("call-id", callId);
    printf("Call-Id: '%s'\n", callId.data());

    UtlString name;
    UtlString value;
    int index = 0;
    printf("\nHeader Parameters:\n");
    while(getHeaderParameter(index, name, value))
    {
        printf("'%s'='%s'\n", name.data(), value.data());
        index++;
    }

    index = 0;
    printf("\nField Parameters:\n");
    while(getFieldParameter(index, name, value))
    {
        printf("'%s'='%s'\n", name.data(), value.data());
        index++;
    }

    index = 0;
    printf("\nURL Parameters:\n");
    while(getUrlParameter(index, name, value))
    {
        printf("'%s'='%s'\n", name.data(), value.data());
        index++;
    }
}
Exemplo n.º 3
0
    // check the validity of an IP address, modify it if necessary
    // (for example, translate "127.0.0.1" to actual IP)
    bool 
    VASTnet::
    validateIPAddress (IPaddr &addr)
    {
        // if address is localhost (127.0.0.1), replace with my detected IP 
        if (addr.host == 0 || addr.host == 2130706433)
            addr.host = getHostAddress ().publicIP.host;

        // TODO: perform other actual checks

        return true;
    }
Exemplo n.º 4
0
void Configuration::setupHostNetwork()
{
#ifdef __arm__
    QProcess::execute("ifconfig", QStringList() << "eth0" << "down");
    usleep(1000*100);
    QProcess::execute("ifconfig", QStringList() << "eth0" << "hw" << "ether" << getMacEther());
    usleep(1000*100);
    QProcess::execute("ifconfig", QStringList() << "eth0" << getHostAddress());
    usleep(1000*100);
    QProcess::execute("ifconfig", QStringList() << "eth0" << "up");
    usleep(1000*500);
#endif
}
int
socketInit(const char *hostname, int _port)
{

  unsigned long host_address;
  int port = htons(_port);

  int sockfd = ::socket(AF_INET, SOCK_STREAM, 0);

  if (socket < 0) {
    printf("socket() failed\n");
    return -1;;
  }    
  if(0 == hostname || !getHostAddress(hostname,&host_address))
  {
    printf("can not get address of host \"%s\"\n", hostname);
    return -1;;
  }

  struct sockaddr_in	serv_addr;
  /*
   * Fill in the structure "serv_addr" with the address of the
   * server that we want to connect with.
   */
  std::memset(&serv_addr, 0, sizeof(serv_addr));
  serv_addr.sin_family      = AF_INET;
  serv_addr.sin_addr.s_addr = host_address; 
  serv_addr.sin_port        = port; 
  /*
   * Connect to the server.
   */
  if (connect(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) 
  {
    printf("%s:%d: error in connect\n", __FILE__, __LINE__);
    return -1;
  }
  return sockfd;
}
void SocketAddr::getHostname( char* outHostname, size_t len ) {
    struct hostent *hostP = NULL;

    if ( !mIsIPv6 ) {
        hostP = gethostbyaddr( (char*) &(((sockaddr_in*) &mAddress)->sin_addr),
                               sizeof( in_addr ),
                               ((sockaddr*) &mAddress)->sa_family );
    }
#if defined(IPV6)
    else {

        hostP = gethostbyaddr( (char*) &(((sockaddr_in6*) &mAddress)->sin6_addr), 
                               sizeof( in6_addr ),
                               ((sockaddr*) &mAddress)->sa_family ); 
    }
#endif

    if ( hostP == NULL ) {
        // in the worst case, just use the dotted decimal IP address
        getHostAddress( outHostname, len );
    } else {
        strncpy( outHostname, hostP->h_name, len );
    }
}
Exemplo n.º 7
0
/*---------------------------------------------------------------------------*/
void clientTest (void)
{
int result;
HTTPSession session;
WinsockStruct s;
/*unsigned long ioctl_arg;*/

	/* allocate a socket */
	s.sd = socket(AF_INET, SOCK_STREAM, 0);
	if (s.sd != INVALID_SOCKET)
	{
		struct sockaddr_in sin;
		char serverName[] = "www.google.com";
		char path[] = "/";
		char method[] = "GET";

		/* try looking up the name via DNS */
		if (getHostAddress(&sin, serverName, 80) >= 0)
		{
			/* connect to the server */
			
			if (connect(s.sd, (PSOCKADDR) &sin, sizeof(sin)) >= 0)
			{
				HTTPRequest request;
				HTTPResponse response;
				HTTP_INT32 len;
				
				/* set the socket to non-blocking mode */
				/*
				ioctl_arg = 1;
				if (ioctlsocket(s.sd, FIONBIO, &ioctl_arg) < 0)
				{
					return (-1);
				}
				*/
				
				/* create an HTTP session */
				result = HTTP_InitSession (&session, 
			                               testHttpReadFn,	
			                               testHttpWriteFn,
			                               &s);
				
				result = HTTP_InitRequest(&session, &request, method, path, 1, 0);
				
				result = HTTP_SetRequestHeaderStr(&request, "Host", serverName);
				result = HTTP_SetRequestHeaderStr(&request, "User-Agent", "HTTP test client");
				result = HTTP_SetRequestHeaderStr(&request, "Accept", "text/*");
				result = HTTP_SetRequestHeaderStr(&request, "Connection", "close");				
				
				result = HTTP_WriteRequest(&session, &request);
				
				HTTP_FreeRequest(&request);

				len = HTTP_ReadResponse(&session, &response, testBuffer, testBufferSize);

				HTTP_ReadHeaders(&session, testProcessHeader, 0, testBuffer + len, testBufferSize - len);

				HTTP_FreeSession(&session);		
			}
		}
		
		/* free the socket */
		closesocket(s.sd);
	}	
}
Exemplo n.º 8
0
/*---------------------------------------------------------------------------*/
void simpleServerTest (void)
{
int result;
HTTPSession session;
SOCKET serverSocket;
WinsockStruct s;
/*unsigned long ioctl_arg;*/

	/* allocate a socket */
	serverSocket = socket(AF_INET, SOCK_STREAM, 0);
	if (serverSocket != INVALID_SOCKET)
	{
		struct sockaddr_in sin;
		char serverName[] = "192.168.1.110";

		/* try looking up the name via DNS */
		if (getHostAddress(&sin, serverName, 1881) >= 0)
		{
			if (bind(serverSocket, (PSOCKADDR) &sin, sizeof(sin)) >= 0)
			{
				if (listen(serverSocket, 5) >= 0)
				{
					while (1)
					{
						s.sd = accept(serverSocket, 0, 0);
						if (s.sd != INVALID_SOCKET)
						{
							HTTPRequest request;
							HTTPResponse response;
							HTTP_INT32 len;
							RTP_TIMESTAMP currentTime;
							char htmlText[1024];

							/* get the current system time/date */
							rtp_date_get_timestamp(&currentTime);

							/* create an HTML document */
							strcpy(htmlText, "<html><body><i>The current time is:</i> ");
							rtp_date_print_time(htmlText + strlen(htmlText), &currentTime, 0);
							strcat(htmlText, "</body></html>");
							
							/* create an HTTP session */
							result = HTTP_InitSession (&session, 
													   testHttpReadFn,	
													   testHttpWriteFn,
													   &s);
							
							/* Read the request */
							len = HTTP_ReadRequest(&session,
												   &request,
												   testBuffer,
												   testBufferSize);

							HTTP_ReadHeaders(&session, testProcessHeader, 0, testBuffer + len, testBufferSize - len);
						 
					 		/* Create a response message */
					 		HTTP_InitResponse(&session,
					 						  &response,
					 						  1, 0,
					 						  200, 
					 						  "OK");
					 						  
							HTTP_SetResponseHeaderStr(&response, "Server", "HTTP Test Server");
							HTTP_SetResponseHeaderStr(&response, "Content-Type", "text/html");
							HTTP_SetResponseHeaderInt(&response, "Content-Length", strlen(htmlText));
							HTTP_SetResponseHeaderStr(&response, "Pragma", "no-cache");
							HTTP_SetResponseHeaderStr(&response, "Cache-Control", "no-cache, must revalidate");
							HTTP_SetResponseHeaderTime(&response, "Date", &currentTime);
							HTTP_SetResponseHeaderTime(&response, "Expires", &currentTime);
							HTTP_SetResponseHeaderTime(&response, "Last-Modified", &currentTime);
							
							/* buffer up to an ethernet MTU */
							HTTP_SetWriteBufferSize(&session, 1452);
							
							/* write the response message, the data, and flush the write buffer */						
							HTTP_WriteResponse(&session, &response);												
							HTTP_Write(&session, htmlText, strlen(htmlText));						
							HTTP_WriteFlush(&session);

							/* free the response and the session */
							HTTP_FreeResponse(&response);						
							HTTP_FreeSession(&session);
							
							/* close the connection */
							closesocket(s.sd);
						}
					}
				}
			}
		}

		/* free the socket */
		closesocket(serverSocket);
	}
}
Exemplo n.º 9
0
/* extraHeaders is either NULL or a string with extra headers separated
 * by '\r\n', ending with '\r\n'.
 */
int httpGetFileDesc(char * hostname, int port, char * remotename,
                    char *extraHeaders) {
    char * buf, *headers = NULL;
    char *status;
    char *hstr;
    int family;
    struct in_addr addr;
    struct in6_addr addr6;
    int sock;
    int rc;
    struct sockaddr_in destPort;
    struct sockaddr_in6 destPort6;
    fd_set readSet;
#ifdef ROCKS
    int bufsize;
#endif /* ROCKS */
    if (port < 0)
        port = 80;

    family = AF_INET;
    rc = getHostAddress(hostname, &addr, family);
    if (rc) {
        family = AF_INET6;
        rc = getHostAddress(hostname, &addr6, family);
        if (rc)
            return rc;
    }

    sock = socket(family, SOCK_STREAM, IPPROTO_IP);
    if (sock < 0) {
        return FTPERR_FAILED_CONNECT;
    }

    if (family == AF_INET) {
        destPort.sin_family = family;
        destPort.sin_port = htons(port);
        destPort.sin_addr = addr;

        if (connect(sock, (struct sockaddr *) &destPort, sizeof(destPort))) {
            close(sock);
            return FTPERR_FAILED_CONNECT;
        }
    } else if (family == AF_INET6) {
        destPort6.sin6_family = family;
        destPort6.sin6_port = htons(port);
        destPort6.sin6_addr = addr6;

        if (connect(sock, (struct sockaddr *) &destPort6, sizeof(destPort6))) {
            close(sock);
            return FTPERR_FAILED_CONNECT;
        }
    }

    if (extraHeaders)
        hstr = extraHeaders;
    else
        hstr = "";

#ifdef ROCKS
    bufsize = strlen(remotename) + strlen(hostname) + strlen(hstr) + 30;

    if ((buf = malloc(bufsize)) == NULL) {
        logMessage(ERROR, "ROCKS:httpGetFileDesc:malloc failed");
        return FTPERR_FAILED_CONNECT;
    }
#else
    buf = alloca(strlen(remotename) + strlen(hostname) + strlen(hstr) + 25);
#endif /* ROCKS */
    sprintf(buf, "GET %s HTTP/1.0\r\nHost: %s\r\n%s\r\n", remotename, hostname, hstr);
    rc = write(sock, buf, strlen(buf));
#ifdef ROCKS
    free(buf);
#endif /* ROCKS */

    rc = read_headers (&headers, &readSet, sock);

    if (rc < 0)
        return rc;

    status = find_status_code (headers);

    if (status == NULL) {
        close(sock);
        return FTPERR_SERVER_IO_ERROR;
    } else if (!strncmp(status, "200", 3)) {
        return sock;
    } else if (!strncmp(status, "301", 3) || !strncmp(status, "302", 3) ||
               !strncmp(status, "303", 3) || !strncmp(status, "307", 3)) {
        struct iurlinfo ui;
        char *redir_loc = find_header (headers, "Location");
        int retval;

        if (redir_loc == NULL) {
            logMessage(WARNING, "got a redirect response, but Location header is NULL");
            close(sock);
            return FTPERR_FILE_NOT_FOUND;
        }

        logMessage(INFO, "redirecting to %s", redir_loc);
        convertURLToUI(redir_loc, &ui);
        retval = httpGetFileDesc (ui.address, -1, ui.prefix, extraHeaders);
        free(redir_loc);
        return retval;
    } else if (!strncmp(status, "403", 3)) {
        close(sock);
        return FTPERR_PERMISSION_DENIED;
    } else if (!strncmp(status, "404", 3)) {
        close(sock);
        return FTPERR_FILE_NOT_FOUND;
#ifdef ROCKS
    } else if (!strncmp(status, "503", 3)) {
         /* A server nack - busy */
         close(sock);
         logMessage(WARNING, "ROCKS:server busy");
         watchdog_reset();
         return FTPERR_FAILED_DATA_CONNECT;
#endif /* ROCKS */
    } else {
        close(sock);
        logMessage(ERROR, "bad HTTP response code: %s", status);
        return FTPERR_BAD_SERVER_RESPONSE;
    }
}
Exemplo n.º 10
0
int ftpOpen(char *host, int family, char *name, char *password,
            char *proxy, int port) {
    static int sock;
    struct in_addr addr;
    struct in6_addr addr6;
    struct sockaddr_in destPort;
    struct sockaddr_in6 destPort6;
    struct passwd * pw;
    char * buf;
    int rc = 0;
    char *userReply;

    if (port < 0) port = IPPORT_FTP;

    if (!name)
        name = "anonymous";

    if (!password) {
        password = "******";
        if (getuid()) {
            pw = getpwuid(getuid());
            if (pw) {
                password = alloca(strlen(pw->pw_name) + 2);
                strcpy(password, pw->pw_name);
                strcat(password, "@");
            }
        }
    }

    if (proxy) {
        if (asprintf(&buf, "%s@%s", name, host) != -1)
            name = buf;
        host = proxy;
    }

    if (family == AF_INET)
        rc = getHostAddress(host, &addr, AF_INET);
    else if (family == AF_INET6)
        rc = getHostAddress(host, &addr6, AF_INET6);

    if (rc)
        return rc;

    sock = socket(family, SOCK_STREAM, IPPROTO_IP);
    if (sock < 0) {
        return FTPERR_FAILED_CONNECT;
    }

    if (family == AF_INET) {
        destPort.sin_family = family;
        destPort.sin_port = htons(port);
        destPort.sin_addr = addr;

        if (connect(sock, (struct sockaddr *) &destPort, sizeof(destPort))) {
            close(sock);
            return FTPERR_FAILED_CONNECT;
        }
    } else if (family == AF_INET6) {
        destPort6.sin6_family = family;
        destPort6.sin6_port = htons(port);
        destPort6.sin6_addr = addr6;

        if (connect(sock, (struct sockaddr *) &destPort6, sizeof(destPort6))) {
            close(sock);
            return FTPERR_FAILED_CONNECT;
        }
    }

    /* ftpCheckResponse() assumes the socket is nonblocking */
    if (fcntl(sock, F_SETFL, O_NONBLOCK)) {
        close(sock);
        return FTPERR_FAILED_CONNECT;
    }

    if ((rc = ftpCheckResponse(sock, NULL))) {
        return rc;     
    }

    if ((rc = ftpCommand(sock, &userReply, "USER", name, NULL))) {
        close(sock);
        return rc;
    }

    /* FTP does not require that USER be followed by PASS.  Anonymous logins
     * in particular do not need any password.
     */
    if (strncmp(userReply, "230", 3) != 0) {
        if ((rc = ftpCommand(sock, NULL, "PASS", password, NULL))) {
            close(sock);
            return rc;
        }
    }

    if ((rc = ftpCommand(sock, NULL, "TYPE", "I", NULL))) {
        close(sock);
        return rc;
    }

    return sock;
}
Exemplo n.º 11
0
//发送HTTP信息
//URL:顾名思义拉URL字符串
//headerReceive:发给服务器的包头
//post:发送的数据的指针
//postLength:发送字符串的长度
//req:回应的数据
//返回值:0、失败 1、成功(好怪异的返回值设置)
int _XHTTPRequest::sendHTTP(char *url,char * headerReceive,unsigned char *post,int postLength,_XHTTPRequestStruct *req)
{
	//SOCKADDR_IN sin;			//用于连接web服务器
	sockaddr_in sin;			//用于连接web服务器
	int sock;					//连接服务器的套接字
	char buffer[512];		
	char protocol[20];			//用于暂存协议
	char host[256];				//用于暂存主机名
	char request[1024];			//用于暂存请求
	int l,port,chars;//,err;
	_XMemBuffer headersBuffer;	//包头缓存
	_XMemBuffer messageBuffer;	//包体缓存
	char headerSend[1024];		//发送包头
	int done;
	
	//解析URL
	parseURL(url,protocol,host,request,&port);
	if(strcmp(protocol,"HTTP"))
	{//目前这个模块只支持HTTP协议
		return 0;
	}

#ifdef XEE_OS_WINDOWS
	if(initSocket() == 0) return 0;
#endif

	//申请套结字
	sock = socket(AF_INET,SOCK_STREAM,0);
	//if(sock == INVALID_SOCKET) return 0;//申请套结字失败
	if(sock < 0) return 0;//申请套结字失败

	//连接到web服务器
	sin.sin_family = AF_INET;
	sin.sin_port = htons((unsigned short)port);
	sin.sin_addr.s_addr = getHostAddress(host);
	if(connect(sock,(sockaddr*)&sin, sizeof(sockaddr_in)))
	{//如果连接失败则返回
		return 0;
	}

	if(!*request)
	{//如果没有请求,则请求为反斜杠
		strcpy(request,"/");
	}

	//发送HTTP包头信息
	if(post == NULL)
	{//如果不是发送,则作为接收处理
		sendString(sock,"GET ");
		strcpy(headerSend, "GET ");
	}else
	{
		sendString(sock,"POST ");
		strcpy(headerSend, "POST ");
	}
	sendString(sock,request);
	strcat(headerSend, request);

	sendString(sock," HTTP/1.0\r\n");
	strcat(headerSend, " HTTP/1.0\r\n");

	sendString(sock,"Accept: image/gif, image/x-xbitmap,"
		" image/jpeg, image/pjpeg, application/vnd.ms-excel,"
		" application/msword, application/vnd.ms-powerpoint,"
		" */*\r\n");
	strcat(headerSend, "Accept: image/gif, image/x-xbitmap,"
		" image/jpeg, image/pjpeg, application/vnd.ms-excel,"
		" application/msword, application/vnd.ms-powerpoint,"
		" */*\r\n");
	sendString(sock,"Accept-Language: en-us\r\n");
	strcat(headerSend, "Accept-Language: en-us\r\n");

	sendString(sock,"Accept-Encoding: gzip, default\r\n");
	strcat(headerSend, "Accept-Encoding: gzip, default\r\n");
	sendString(sock,"User-Agent: Neeao/4.0\r\n");
	strcat(headerSend, "User-Agent: Neeao/4.0\r\n");

	if(postLength)
	{
		sprintf(buffer,"Content-Length: %ld\r\n",postLength);
		sendString(sock,buffer);
		strcat(headerSend, buffer);
	}
	//sendString(sock,"Cookie: mycookie=blablabla\r\n");
	// printf("Cookie: mycookie=blablabla\r\n");
	sendString(sock,"Host: ");
	strcat(headerSend, "Host: ");

	sendString(sock,host);
	strcat(headerSend, host);

	sendString(sock,"\r\n");
	strcat(headerSend, "\r\n");

	if((headerReceive != NULL) && *headerReceive)
	{
		sendString(sock,headerReceive);
		strcat(headerSend, headerReceive);
	}

	sendString(sock,"\r\n"); // Send a blank line to signal end of HTTP headerReceive
	strcat(headerSend, "\r\n");

	if((post != NULL) && postLength)
	{//发送需要发送的内容
		send(sock,(const char*)post,postLength,0);
		post[postLength] = '\0';

		strcat(headerSend, (const char*)post);
	}

	//strcpy(req->headerSend, headerSend);
	req->headerSend = (char*) malloc( sizeof(char*) * strlen(headerSend));
	if(req->headerSend != NULL)
		strcpy(req->headerSend, (char*) headerSend );

	//下面开始解收包头
	memBufferCreate(&headersBuffer );
	chars = 0;
	done = 0;

	while(!done)
	{
		l = recv(sock,buffer,1,0);
		if(l < 0) done = 1;//接受完成

		switch(*buffer)
		{
		case '\r':
			break;
		case '\n':
			if(chars==0)
			{//接受完成
				done = 1;
			}
			chars=0;
			break;
		default:
			chars++;
			break;
		}

		memBufferAddByte(&headersBuffer,*buffer);
	}
	//将接受到的包头保存起来
	req->headerReceive = (char*) headersBuffer.buffer;
	*(headersBuffer.position) = 0;

	//下面接受包体
	memBufferCreate(&messageBuffer); // Now read the HTTP body
	do
	{
		l = recv(sock,buffer,sizeof(buffer)-1,0);
		if(l<0)
		{//包体接受完成
			break;
		}
		*(buffer + l)=0;
		memBufferAddBuffer(&messageBuffer, (unsigned char*)&buffer, l);
	}while(l > 0);

	*messageBuffer.position = 0;
	req->message = (char*) messageBuffer.buffer;
	req->messageLength = (messageBuffer.position - messageBuffer.buffer);

	//交互完毕之后关闭socket
#ifdef XEE_OS_WINDOWS
	closesocket(sock);
#endif
#ifdef XEE_OS_LINUX
	close(sock);
#endif

	return 1;
}
Exemplo n.º 12
0
void BmNetworkTCPClient::connectTo()
{
    if ( !isConnected() )
        mSocket->connectToHost( getHostAddress(), getPort() );
}
Exemplo n.º 13
0
std::string Inet6Address::toString() const
{
    std::stringstream strm;
    strm << getHostName() << " IPv6 (" << getHostAddress() << ")";
    return strm.str();
}