Esempio n. 1
0
extern	int
InitServerPort(
	Port	*port,
	int		back)
{
	int		fd;

ENTER_FUNC;
	fd = BindSocket(port,SOCK_STREAM);
	if		(  listen(fd,back)  <  0  )	{
		shutdown(fd, 2);
		Error("INET Domain listen");
	}
LEAVE_FUNC;
	return	(fd);
}
Esempio n. 2
0
int main(int argc, char **argv) {
	int cli;
	int sock = BindSocket(12345);
	struct config conf;
	conf.store = store_open("tracker.db");
	conf.max_peer_return=50;
	conf.min_interval=300;
	conf.max_peer_return=48;
	struct event_base *base = event_init();
	struct evhttp *httpd;
	httpd = evhttp_new(base);
	cli = evhttp_accept_socket(httpd, sock);
	evhttp_set_gencb(httpd, tracker, (void *)&conf);
	event_base_dispatch(base);

	return 0;
}
Esempio n. 3
0
////////////////////////////////////////////////////////////////////////////////
/// 名   称:TCPSocket::Init
/// 功   能:初始化对象
/// 参   数:void
/// 返回 值:bool                       public
////////////////////////////////////////////////////////////////////////////////
bool TCPSocket::Init()
{
    // 读取配置文件
    if (!LoadConfig())
    {
        return false;
    }
    // 设置读写ID口文件最大数
    SetLimitMax();
    // 显示当前Socket配置情况
    if (!ShowSocketStatus())
    {
        return false;
    }
    // 初始化线程池
    if (!ThreadPollInit())
    {
        return false;
    }
    // 屏蔽多重发送的报错信号
    if (!MaskSignal())
    {
        return false;
    }
    // 创建Socket
    if (!CreateSocket())
    {
        return false;
    }
    // 创建Epoll
    if (!CreateEpoll())
    {
        return false;
    }
    // 绑定Socket
    if (!BindSocket())
    {
        return false;
    }
    // 开启监听该Socket
    if (!ListenSocket())
    {
        return false;
    }
    return true;
}
Esempio n. 4
0
CNetManager::CNetManager(string strIp, string strPort)
: m_bRecv(false)
, m_bSend(false)
, m_hRecv(INVALID_HANDLE_VALUE)
, m_hSend(INVALID_HANDLE_VALUE)
, m_bAlreadyDoConn(false)
{
	LogObject;

	if(m_pNet)
		return;

	u_short nPort = (u_short)atoi(strPort.c_str());

	m_strIp = strIp;
	m_uPort = nPort;

	WORD VersionRequest = MAKEWORD(1,1);
	WSADATA wsadata;
	int err;

	err=WSAStartup(VersionRequest,&wsadata);

	if (!err)
	{
		LogOutInfo("已打开套接字");
	} 
	else
	{
		//进一步绑定套接字
		LogOutError("嵌套字未打开!");
		return;
	}


	BindSocket();

	m_pNet = this;
}
Esempio n. 5
0
//
// Creates the server and client sockets, and binds the server socket.
//
ReturnVal NetAsyncTCP::Create( BOOL create_server )
{
	SOCKET		*s;
	SOCKADDR_IN	*address;
	
	if ( create_server )
	{
		s = &server_socket;
		address = &server_address;
	}
	else
	{
		s = &client_socket;
		address = &client_address;
	}

	if ( CreateSocket( s ) != ReturnSuccess || 
		BindSocket( s, address ) != ReturnSuccess )
	{
		return ReturnError;
	}

	return ReturnSuccess;
}
Esempio n. 6
0
//
/// This BindSocket simply binds with the previously defined member data socket
/// address.
//
int TSocket::BindSocket()
{
  return BindSocket(SocketAddress);
}
Esempio n. 7
0
RelayOutput::RelayOutput(SourceInfo* inInfo, UInt32 inWhichOutput, RelaySession* inRelaySession, Bool16 isRTSPSourceInfo)
	: fRelaySession(inRelaySession),
	fOutputSocket(NULL, Socket::kNonBlockingSocketType),
	fNumStreams(inRelaySession->GetSourceInfo()->GetNumStreams()),  // use the reflector session's source info
	fOutputInfo(*inInfo->GetOutputInfo(inWhichOutput)),
	fQueueElem(),
	fFormatter(&fHTMLBuf[0], kMaxHTMLSize),
	fPacketsPerSecond(0),
	fBitsPerSecond(0),
	fLastUpdateTime(0),
	fTotalPacketsSent(0),
	fTotalBytesSent(0),
	fLastPackets(0),
	fLastBytes(0),
	fClientSocket(NULL),
	fClient(NULL),
	fDoingAnnounce(false),
	fValid(true),
	fOutgoingSDP(NULL),
	fAnnounceTask(NULL),
	fRTSPOutputInfo(NULL)
{
	Assert(fNumStreams > 0);

	fQueueElem.SetEnclosingObject(this);
	fStreamCookieArray = NEW void*[fNumStreams];
	fTrackIDArray = NEW UInt32[fNumStreams];
	fOutputInfo.fPortArray = NEW UInt16[fNumStreams];//copy constructor doesn't do this
	::memset(fOutputInfo.fPortArray, 0, fNumStreams * sizeof(UInt16));

	// create a bookmark for each stream we'll reflect
	this->InititializeBookmarks(inRelaySession->GetNumStreams());

	// Copy out all the track IDs for each stream
	for (UInt32 x = 0; x < fNumStreams; x++)
	{
		fTrackIDArray[x] = inRelaySession->GetSourceInfo()->GetStreamInfo(x)->fTrackID;
		fStreamCookieArray[x] = inRelaySession->GetStreamCookie(fTrackIDArray[x]);
	}

	// Copy the contents of the output port array

	if (inInfo->GetOutputInfo(inWhichOutput)->fPortArray != NULL)
	{
		UInt32 copySize = fNumStreams;
		if (fOutputInfo.fNumPorts < fNumStreams)
			copySize = fOutputInfo.fNumPorts;
		::memcpy(fOutputInfo.fPortArray, inInfo->GetOutputInfo(inWhichOutput)->fPortArray, copySize * sizeof(UInt16));
	}
	else if (fOutputInfo.fBasePort != 0)
	{
		for (UInt32 y = 0; y < fNumStreams; y++)
			fOutputInfo.fPortArray[y] = (UInt16)(fOutputInfo.fBasePort + (y * 2));
	}

	OS_Error err = BindSocket();
	if (err != OS_NoErr)
	{
		fValid = false;
		return;
	}

	RTSPOutputInfo* rtspInfo = NULL;
	if (isRTSPSourceInfo)
	{
		// in the case of the announce source info, the passed in source info will have the new
		// output information, but only the session's source info will have the sdp and url.
		RTSPSourceInfo* rtspSourceInfo = (RTSPSourceInfo *)(inInfo);
		Assert(rtspSourceInfo != NULL);
		RTSPSourceInfo* sessionSourceInfo = (RTSPSourceInfo *)(inRelaySession->GetSourceInfo());
		Assert(sessionSourceInfo != NULL);

		rtspInfo = rtspSourceInfo->GetRTSPOutputInfo(inWhichOutput);
		if (rtspInfo->fIsAnnounced)
		{
			fRTSPOutputInfo = NEW RTSPOutputInfo();
			fRTSPOutputInfo->Copy(*rtspInfo);

			fDoingAnnounce = true;
			// set up rtsp socket and client
			fClientSocket = new TCPClientSocket(Socket::kNonBlockingSocketType);
			fClient = new RTSPClient(fClientSocket, false, RelaySession::sRelayUserAgent);

			// set up the outgoing socket
			fClientSocket->Set(fOutputInfo.fDestAddr, rtspInfo->fAnnouncePort);
			int sndBufSize = 32 * 1024;
			int rcvBufSize = 1024;
			fClientSocket->SetOptions(sndBufSize, rcvBufSize);

			// set up the client object
			StrPtrLen url;
			if ((rtspInfo->fDestURl != NULL) && (strlen(rtspInfo->fDestURl) > 0))
				url.Set(rtspInfo->fDestURl);
			else
				url.Set(sessionSourceInfo->GetSourceURL());

			fClient->Set(url);

			fClient->SetTransportMode(RTSPClient::kPushMode);
			fClient->SetName(rtspInfo->fUserName);
			fClient->SetPassword(rtspInfo->fPassword);

			UInt32 len;
			fOutgoingSDP = sessionSourceInfo->GetAnnounceSDP(fOutputInfo.fDestAddr, &len);
			fAnnounceState = kSendingAnnounce;
			fCurrentSetup = 0;
			fAnnounceTask = new RelayAnnouncer(this);    // this will now go and run the async announce
			fAnnounceTask->Signal(Task::kStartEvent);
		}
	}

	// Write the Output HTML
	// Looks like: Relaying to: 229.49.52.102, Ports: 16898 16900 Time to live: 15
	static StrPtrLen sHTMLStart("Relaying to: ");
	static StrPtrLen sPorts(", Ports: ");
	static StrPtrLen sTimeToLive(" Time to live: ");
	static StrPtrLen sHTMLEnd("<BR>");

	// First, format the destination addr as a dotted decimal string
	char theIPAddrBuf[20];
	StrPtrLen theIPAddr(theIPAddrBuf, 20);
	struct in_addr theAddr;
	theAddr.s_addr = htonl(fOutputInfo.fDestAddr);
	SocketUtils::ConvertAddrToString(theAddr, &theIPAddr);

	// Begin writing the HTML
	fFormatter.Put(sHTMLStart);
	fFormatter.Put(theIPAddr);
	fFormatter.Put(sPorts);

	for (UInt32 y = 0; y < fNumStreams; y++)
	{
		// Write all the destination ports
		fFormatter.Put(fOutputInfo.fPortArray[y]);
		fFormatter.PutSpace();
	}

	if (SocketUtils::IsMulticastIPAddr(inInfo->GetOutputInfo(inWhichOutput)->fDestAddr))
	{
		// Put the time to live if this is a multicast destination
		fFormatter.Put(sTimeToLive);
		fFormatter.Put(fOutputInfo.fTimeToLive);
	}
	fFormatter.Put(sHTMLEnd);

	// Setup the StrPtrLen to point to the right stuff
	fOutputInfoHTML.Ptr = fFormatter.GetBufPtr();
	fOutputInfoHTML.Len = fFormatter.GetCurrentOffset();

	OSMutexLocker locker(&sQueueMutex);
	sRelayOutputQueue.EnQueue(&fQueueElem);

	SetupRelayOutputObject(rtspInfo);
}
Esempio n. 8
0
File: net.c Progetto: ewirch/qfusion
/*
* NET_IP_OpenSocket
*/
static qboolean NET_IP_OpenSocket( socket_t *sock, const netadr_t *address, socket_type_t socktype, qboolean server )
{
    int newsocket;
    const char *proto, *stype;

    assert( sock && !sock->open );
    assert( address );

    if( address->type == NA_IP )
        proto = "IP";
    else if( address->type == NA_IP6 )
        proto = "IPv6";
    else
    {
        NET_SetErrorString( "Invalid address type" );
        return qfalse;
    }

    if( socktype == SOCKET_UDP )
        stype = "UDP";
#ifdef TCP_SUPPORT
    else if( socktype == SOCKET_TCP )
        stype = "TCP";
#endif
    else
    {
        NET_SetErrorString( "Invalid socket type" );
        return qfalse;
    }

    if( NET_IsAnyAddress( address ) )
    {
        Com_Printf( "Opening %s/%s socket: *:%hu\n", stype, proto, NET_GetAddressPort( address ) );
    }
    else
    {
        Com_Printf( "Opening %s/%s socket: %s\n", stype, proto, NET_AddressToString( address ) );
    }

    if( ( newsocket = OpenSocket( socktype, ( address->type == NA_IP6 ? qtrue : qfalse ) ) ) == INVALID_SOCKET )
        return qfalse;

    // make it non-blocking
    if( !NET_SocketMakeNonBlocking( newsocket ) )
    {
        Sys_NET_SocketClose( newsocket );
        return qfalse;
    }

    if( socktype == SOCKET_UDP )
    {
        // make it broadcast capable
        if( !NET_SocketMakeBroadcastCapable( newsocket ) )
        {
            Sys_NET_SocketClose( newsocket );
            return qfalse;
        }
    }

    // wsw : pb : make it reusable (fast release of port when quit)
    /*if( setsockopt(newsocket, SOL_SOCKET, SO_REUSEADDR, (char *)&i, sizeof(i)) == -1 ) {
    SetErrorStringFromErrno( "setsockopt" );
    return 0;
    }*/

    if( !BindSocket( newsocket, address ) )
    {
        Sys_NET_SocketClose( newsocket );
        return qfalse;
    }

    sock->open = qtrue;
    sock->type = socktype;
    sock->address = *address;
    sock->server = server;
    sock->handle = newsocket;

    return qtrue;
}
int
main(int argc, char *argv[])
{
       // int  sock, rtsock, count, params[2], fd,index_sp,mimo_flag=0,mimo_flag1=0,mimo_flag2=0, average[10];
	int  sock, rtsock, i,j, counta=0, countb=0, countc=0, count, params[2], fd,index_sp,mimo_flag=0,mimo_flag1=0,mimo_flag2=0, average[10];
	int  addrLen,k,sum=0,qsum=0,sum1=0,qsum1=0,sum2=0,qsum2=0, number=0, add=0;
	FILE* f;
        double alfa;
        float a,b,c,Xmn,Ymn,Ymn1,Ymn2,Xinput,Yinput,Distance,dp1,dp2,tambah, averageda, averagedb, averagedc, averaged=0.0;
	struct sockaddr_in addr;
	char *s, s1[1024];

         if((f=fopen("/root/ssf.c","r+"))==NULL)
		{
		printf("cannot open this file\n");exit(-1);
		}
	if(argc < 2) {
		fprintf(stderr, "usage: Rtrg_gps [ru|rr|tu|tr] [<address>]\n");
		exit(-1);
	}
	s = (argc < 3)? "" : argv[2];
	if(strcmp(argv[1], "ru") == 0) {
		if((sock = BindSocket(CreateUDPSocket(), s)) < 0) {
			exit(-1);
		}
		addrLen = sizeof(addr);
		if(getsockname(sock, &addr, &addrLen) < 0 ) {
		    	close(sock);
		    	return -1;
		}
	
		
	       printf("Rtrg_gps will receive request at this address %s\n", EncodeIPAddress(s1, &addr));
               for(;;){
              recv(sock,&index_sp, sizeof(index_sp), 0);
               //printf("I receive ur index \n");
              for(i=0; i< index_sp;i++)   {
              recv(sock, &p[i], sizeof(p), 0);
              if(strcmp((p[i].essid,"mimos")==0)&&counta<3)
               // {a=p[i].dis;mimo_flag++;fprintf(f,"%s ESSID: %s Signal level: %d Distance: %f\n",p[i].mac,p[i].essid,p[i].sl,a);
                 {a=p[i].dis;tambah=p[i].sl;mimo_flag++;fprintf(f,"%s ESSID: %s Signal level: %d Distance: %f\n",p[i].mac,p[i].essid,tambah,a);
                     a=a+p[i].dis;
                     counta++; 


            //   add += p[i].sl;
            //   averaged = (float)add / 10;
              
              // n[i]=0;    
              // a+= n[i];  
            //  printf(" entah macam mana %f\n", averaged);
}
              else if(strcmp((p[i].essid,"mimos1")==0)&&countb<3) 
               {b=p[i].dis;mimo_flag1++;fprintf(f,"%s ESSID: %s Signal level: %d Distance: %f\n",p[i].mac,p[i].essid,p[i].sl,b);

                     b=b+p[i].dis;
                     countb++; 


}
              else if(strcmp((p[i].essid,"mimos2")==0)&&countc<3) 
               {c=p[i].dis;mimo_flag2++;fprintf(f,"%s ESSID: %s Signal level: %d Distance: %f\n",p[i].mac,p[i].essid,p[i].sl,c);

                     c=c+p[i].dis;
                     countc++; 

}
              printf("%s ESSID: %s Signal level: %d Distance: %f\n",p[i].mac,p[i].essid,p[i].sl,p[i].dis);	     
               //add += p[i].sl;
               //averaged = (float)add / i;
              
              // n[i]=0;    
              // a+= n[i];  
              //printf(" %f\n", averaged);

}
}

               add += tambah;
               averaged = (float)add / 3;
               printf(" entah macam mana %f\n", averaged);

//printf("enter referend point x,y : " );
//scanf  ("%f,%f", &Xinput, &Yinput);        // key in location of other point
//printf ("You enter %f, %f \n", Xinput, Yinput);
                    
             // calculate mobile node location
            if(mimo_flag > 0 && mimo_flag1>0 && mimo_flag2 >0 ){
     
             alfa=acos((a*a+100-b*b)/(20*a));
             if( isnan(alfa)==0){
             Xmn=a*cos(alfa);Ymn1=a*sin(alfa);Ymn2=-Ymn1;
 	     Distance=sqrt(((Xmn-Xinput)*(Xmn-Xinput))+((Ymn-Yinput)*(Ymn-Yinput)));
             dp1=sqrt(Xmn*Xmn + (10-Ymn1)*(10-Ymn1));
             dp2=sqrt(Xmn*Xmn + (10-Ymn2)*(10-Ymn2));
  	     if (fabsf(dp1-c) < fabsf(dp2-c))
             Ymn=Ymn1;
             else
             Ymn=-Ymn2;
 	     if ( Xmn < 0 )
 	     Xmn = -Xmn;
             else
             Xmn = Xmn;



printf("alfa is %f, dp1 is %f,dp2 is %f. The location of mobile node is (%f,%f) \n",alfa,dp1,dp2,Xmn,Ymn);
fprintf(f,"The location of mobile node is (%f,%f)\n",Xmn,Ymn);

 //	{ 	
 //	Ymn=Ymn1;
 //	Distance=sqrt((Xmn-Xinput)*(Xmn-Xinput)+(Ymn1-Yinput)*(Ymn1-Yinput)); //measure the distance
 //	}
 //       else
 //       {	 
 //	Ymn=Ymn2;
 //	Distance=sqrt((Xmn-Xinput)*(Xmn-Xinput)+(Ymn2-Yinput)*(Ymn2-Yinput)); //measure the distance
 //	}

//printf("alfa is %f, dp1 is %f,dp2 is %f. The location of mobile node is (%f,%f). The distance between mobile node (%f,%f) and (%f,%f) is %f \n",alfa,dp1,dp2,Xmn,Ymn, Xinput, Yinput, Xmn, Ymn, Distance);
//fprintf(f,"The location of mobile node is , and the nearest distance is \n");
//fclose(f);
//return (i=0); 

}
else
printf("Please wait ...... \n");                    
} //end if

else
printf("Please wait ...... \n");

//} //end for loop
} //end infinate for loop	 
//}	
}
Esempio n. 10
0
//
// Client () performs the connection-less/connection-oriented client
// related tasks
//
void Client()
{                                                
    SOCKADDR_IPX  sa_ipx,                 // client address
                  sa_ipx_server;          // server address 
    char          chBuffer[MAX_DATA_LEN]; // data buffer 
    int           ret, 
                  cb;
    DWORD         i;
        
    CreateSocket();
    //
    // Bind to a local address and endpoint
    //
    BindSocket(&sa_ipx, pszLocalAddress, NULL);
    
    if (pszServerEndpoint == NULL)
    {
        printf("Server Endpoint must be specified....Exiting\n");
        ExitProcess(-1);
    }
    // Fill the sa_ipx_server address address with server address and endpoint
    //
    if (pszServerAddress != NULL)
    {
        FillIpxAddress ( &sa_ipx_server, pszServerAddress, pszServerEndpoint);
    }
    else
    {
        printf("Server Address must be specified....Exiting\n");
        ExitProcess(-1);
    }
    // Check the Specified protocol. Call connect() if a connection oriented 
    // protocol is specified
    //
    if (chProtocol != 'd')
    {
        printf("Connecting to Server -");
        PrintIpxAddress ( sa_ipx_server.sa_netnum, sa_ipx_server.sa_nodenum );
        //
        // Connect to the server
        //
        ret = connect(sock, (SOCKADDR *) &sa_ipx_server, sizeof sa_ipx_server);
        if (ret == SOCKET_ERROR)
        {
            printf("connect() failed: %d\n", WSAGetLastError());
            return;
        }
        printf("Connected to Server Address - ");
        PrintIpxAddress( sa_ipx_server.sa_netnum, sa_ipx_server.sa_nodenum );
        //
        // Send data to the specfied server
        //
        memset(chBuffer, '*', dwNumBytes);
        chBuffer[dwNumBytes] = 0;

	for(i=0; i < dwNumToSend ;i++)
	{
            ret = SendData(sock, chBuffer);
            if (ret == 0)
                return;
            else if (ret == -1)
                return;
            printf("%d bytes of data sent\n", ret);
            //
            // Receive data from the server
            //
            ret = ReceiveData(sock, chBuffer);
            if (ret == 0)
                return;
            else if (ret == -1)
                return;
            //
            // Print the contents of received data
            //
            chBuffer[ret] = '\0';
            printf("%d bytes of data received->%s\n", ret, chBuffer);
	}
    }
    else
    {
        // Send a datagram to the specified server
        //
        memset(chBuffer, '*', dwNumBytes);
        chBuffer[dwNumBytes] = 0;

	for(i=0; i < dwNumToSend ;i++)
	{
            ret = SendDatagram(sock, chBuffer, &sa_ipx_server);
            if (ret == -1)
                return;
            printf("%d bytes of data sent\n", ret);
            //
            // Receive a datagram from the server
            //
            cb = sizeof(sa_ipx_server);
            ret = ReceiveDatagram(sock, chBuffer, &sa_ipx_server, &cb);
            if (ret == -1)
                return;
            //
            // Print the contents of received data
            //
            chBuffer[ret] = '\0';
            printf("%d bytes of data received->%s\n", ret, chBuffer);
	}
    }
    return;
}
Esempio n. 11
0
//
// Server () performs the connection-less/connection-oriented server
// related tasks
//
void Server()
{                        
    SOCKADDR_IPX  sa_ipx,                 // Server address
                  sa_ipx_client;          // Client address 
    char          chBuffer[MAX_DATA_LEN]; // Data buffer
    int           ret, 
                  cb;
        
    CreateSocket ( );
    //
    // Bind to a local address and endpoint
    //
    BindSocket(&sa_ipx, pszLocalAddress, pszServerEndpoint);
    //
    // Check the Specified protocol. Call listen(), accept() if a connection 
    // oriented protocol is specified
    //
    if (chProtocol != 'd')
    {
        ret = listen(sock, 5);
        if (ret == SOCKET_ERROR)
        {
            printf("listen() failed: %d\n", WSAGetLastError());
            return;
        }
        printf("Waiting for a Connection...\n");
        //
        // Wait for a connection
        //
	while (1)
	{
            cb = sizeof(sa_ipx_client);
            newsock = accept(sock, (SOCKADDR *) &sa_ipx_client, &cb);

            if (newsock == INVALID_SOCKET)
            {
                printf("accept() failed: %d\n", WSAGetLastError());
                return;
            }
            // Print the address of connected client
            //
            printf("Connected to Client Address - ");
            PrintIpxAddress(sa_ipx_client.sa_netnum, sa_ipx_client.sa_nodenum);

            while (1)
            {
                // Receive data on newly created socket
                //
                ret = ReceiveData(newsock, chBuffer);
                if (ret == 0)
                    break;
                else if (ret == -1)
                    return;                
                //
                // Print the contents of received data
                //
                chBuffer[ret] = '\0';
                printf("%d bytes of data received->%s\n", ret, chBuffer);
                //
                // Send data on newly created socket
                //
                ret = SendData(newsock, chBuffer);
                if (ret == 0)
                    break;
                else if (ret == -1)
                    return;
                printf("%d bytes of data sent\n", ret);
            }
	    closesocket(newsock);
        }
    }
    else  // Server will recv and send datagrams
    {
        // Receive a datagram on the bound socket
        //
        while (1)
        {
            cb = sizeof (sa_ipx_client);
            ret = ReceiveDatagram(sock, chBuffer, &sa_ipx_client, &cb);
            if (ret == -1)
                return;
            //
            // Print the contents of received datagram and the senders address
            //
            printf("Message Received from Client Address - ");
            PrintIpxAddress( sa_ipx_client.sa_netnum, sa_ipx_client.sa_nodenum );
            chBuffer[ret] = '\0';

            printf("%d bytes of data received->%s\n", ret, chBuffer);
            //
            // Echo the datagram on the bound socket to the client
            //
            ret = SendDatagram(sock, chBuffer, &sa_ipx_client);
            if (ret == -1)
                return;
            printf("%d bytes of data sent\n", ret);
        }
	closesocket(newsock);
    }
    return;
}
int
main(int argc, char *argv[])
{

//add server

        int sockfd, new_fd;  // listen on sock_fd, new connection on new_fd
	struct sockaddr_storage their_addr; // connector's address information
	socklen_t sin_size;
	struct sigaction sa;
	int yes=1;
	char l[INET6_ADDRSTRLEN];
	int rv;

//until here





       int  sock, rtsock, i,j, sd, count, params[2], fd,index_sp,mimo_flag=0,mimo_flag1=0,mimo_flag2=0, average[10];
	int  addrLen,k,sum=0,qsum=0,sum1=0,qsum1=0,sum2=0,qsum2=0, number=0, add=0;
        int   a_macadd1, a_macadd2, a_macadd3, a_macadd4, a_macadd5,a_macadd6;
	
        FILE *f;
        FILE *ff;
        FILE *fff;
        double alfa;
        
        float a,b,c,Xmn,Ymn,Ymn1,Ymn2,X1,X2,X3,X4,X5,Y1,Y2,Y3,Y4,Y5,Distance,dp1,dp2,tambah, averaged=0.0;
        float Distance1,mobile_A,mobile_B,Distance15,Distance2,Distance23,Distance24,Distance25;
        float Distance3,Distance31,Distance32,Distance34,Distance35,Distance41,Distance42,Distance43,Distance45;
        float Distance51,Distance52,Distance53,Distance54,Distance4,Distance5,Distance6,Distance7,Distance8,Distance9;

	struct sockaddr_in addr;
        struct hostent *hp;
        struct in_addr *ptr;

        char nearestmobile, mobile1, mobile2, mobile3, mobile4, mobile5;
	char *s, s1[1024];


        if((f=fopen("/root/ssf.c","r+"))==NULL)
		{
		printf("entah\n");exit(-1);
		}

	if(argc < 2) {
		fprintf(stderr, "usage: Rtrg_gps [ru|rr|tu|tr] [<address>]\n");
		exit(-1);
	}
	s = (argc < 3)? "" : argv[2];
	if(strcmp(argv[1], "ru") == 0) {
		if((sock = BindSocket(CreateUDPSocket(), s)) < 0) {
			exit(-1);
		}
		addrLen = sizeof(addr);
		if(getsockname(sock, &addr, &addrLen) < 0 ) {
		    	close(sock);
		    	return -1;
		}
	
		
	       printf("Rtrg_gps will receive request at this address %s\n", EncodeIPAddress(s1, &addr));
               for(;;){
              recv(sock,&ind.index_sp, sizeof(ind.index_sp), 0);
               //printf("I receive ur index \n");
              for(i=0; i< ind.index_sp;i++)   {
              recv(sock, &p[i], sizeof(p), 0);


              if(strcmp(p[i].essid,"mimos")==0)
              {
              a=p[i].dis;tambah=p[i].sl;mimo_flag++;
              fprintf(f,"%s ESSID: %s Signal level: %d Distance: %f Got from : %s\n",p[i].mac,p[i].essid,p[i].sl,a,ind.mac);
              }
              else if(strcmp(p[i].essid,"mimos1")==0) 
               {b=p[i].dis;mimo_flag1++;fprintf(f,"%s ESSID: %s \nSignal level: %d \n Distance: %f Got from : %s\n",p[i].mac,p[i].essid,p[i].sl,b,ind.mac);}
              else if(strcmp(p[i].essid,"mimos2")==0) 
               {c=p[i].dis;mimo_flag2++;fprintf(f,"%s ESSID: %s Signal level: %d Distance: %f Got from : %s\n",p[i].mac,p[i].essid,p[i].sl,c,ind.mac);}
              printf("%s ESSID: %s Signal level: %d Distance: %f Got from : %s\n",p[i].mac,p[i].essid,p[i].sl,p[i].dis,ind.mac);



//add server
                        
		        inet_ntop(their_addr.ss_family,
			get_in_addr((struct sockaddr *)&their_addr),
			s, sizeof s);
		        printf("server: %s\n", s);  

//until here
                   
             // calculate mobile node location
            if(mimo_flag > 0 && mimo_flag1>0 && mimo_flag2 >0 ){
     
             alfa=acos((a*a+25-b*b)/(10*a));
             if( isnan(alfa)==0){
             Xmn=a*cos(alfa);Ymn1=a*sin(alfa);Ymn2=-Ymn1;
             dp1=sqrt(Xmn*Xmn + (5-Ymn1)*(5-Ymn1));
             dp2=sqrt(Xmn*Xmn + (5-Ymn2)*(5-Ymn2));
  	     if (fabsf(dp1-c) < fabsf(dp2-c))
             Ymn=Ymn1;
             else
             Ymn=-Ymn2;
 	     if ( Xmn < 0 )
 	     Xmn = -Xmn;
             else
             Xmn = Xmn;

printf("alfa is %f, dp1 is %f,dp2 is %f. The location of mobile node is (%f,%f) \n",alfa,dp1,dp2,Xmn,Ymn);
fprintf(f,"The location of mobile node is (%f,%f)\n",Xmn,Ymn);

 	Distance1=sqrt(((Xmn-3.5)*(Xmn-3.5))+((Ymn-1.2)*(Ymn-1.2)));      //mobile with kyle
        Distance2=sqrt(((Xmn-2.8)*(Xmn-2.8))+((Ymn-8.7)*(Ymn-8.7)));      //mobile node with sally
        Distance3=sqrt(((3.5-2.8)*(3.5-2.8))+((1.2-8.7)*(1.2-8.7)));      //kyle with sally
        Distance4=sqrt(((3.5-0)*(3.5-0))+((1.2-0)*(1.2-0)));              //kyle with mimos
        Distance5=sqrt(((2.8-0)*(2.8-0))+((8.7-0)*(8.7-0)));              //sally with mimos
        Distance6=sqrt(((2.8-10)*(2.8-10))+((8.7-0)*(8.7-0)));              //sally with mimos2
        Distance7=sqrt(((3.5-10)*(3.5-10))+((1.2-0)*(1.2-0)));              //kyle with mimos2
        Distance8=sqrt(((3.5-0)*(3.5-0))+((1.2-10)*(1.2-10)));              //kyle with mimos1
        Distance9=sqrt(((2.8-0)*(2.8-0))+((8.7-10)*(8.7-10)));              //sally with mimos1


printf("Distance for mobile node with Kyle is %f \n",Distance1);		
fprintf(f,"Distance for mobile node with Kyle is %f \n",Distance1);
printf("Distance for mobile node with Sally is %f \n",Distance2);		
fprintf(f,"Distance for mobile node with Sally is %f \n",Distance2);
printf("Distance for Klye with Sally is %f \n",Distance3);		
fprintf(f,"Distance for Klye with Sally is %f \n",Distance3);
	
//nearest distance

{
if (Distance1>Distance2){
        ff=fopen("answer.c","w");
        fff=fopen("data.c","r+");
        nearestmobile = mobile_B;
        printf ("The nearest mobile is Sally with distance %f\n ", Distance2);
        fprintf (f,"The nearest mobile is Sally with distance %f\n ", Distance2);
        fprintf(ff,"*****@*****.**");
        fprintf(fff,"-----------------------------------------------------------------------------------\n");
        fprintf(fff,"SIP URI			 	 	LOCATION\n");
        fprintf(fff,"%s 		    (%f,%f) \n",ind.mac,Xmn,Ymn);
        fprintf(fff,"[email protected]  		 	(2.8,8.7) \n");
        fprintf(fff,"[email protected]  		 	(3.5,1.2) \n");
        fprintf(fff,"-----------------------------------------------------------------------------------\n");
        fprintf(fff,"\n");
        fprintf(fff,"\n");	
        fprintf(fff,"******************************************************************************************************************************\n");
        fprintf(fff,"		 	%s 	 	 	[email protected] 	 	 	[email protected]\n",ind.mac);
        fprintf(fff,"%s 	 	X			  	      %f                                %f \n",ind.mac,Distance2,Distance1);
        fprintf(fff,"Sally 	 	 	   %f			                 X                                    %f \n",Distance2,Distance3);
        fprintf(fff,"Kyle 	 	 	   %f			              %f                                   %f \n",Distance1,Distance3);
        fprintf(fff,"mimos 	 	 	   %f			              %f                                      %f \n",a,Distance4,Distance5);
        fprintf(fff,"mimos1 	 	 	   %f			              %f                                      %f \n",b,Distance9,Distance8);
        fprintf(fff,"mimos2 	 	 	   %f			              %f                                      %f \n",c,Distance6,Distance7);
        fprintf(fff,"******************************************************************************************************************************\n");		
        fclose(ff);
        fclose(fff);
         }
          else {
          ff=fopen("answer.c","w");
          fff=fopen("data.c","r+");
          nearestmobile = mobile_A;
          printf ("The nearest mobile is Kyle with distance %f\n ", Distance1);
          fprintf (f,"The nearest mobile is Kyle with distance %f\n ", Distance1);
          fprintf(ff,"*****@*****.**");
        fprintf(fff,"-----------------------------------------------------------------------------------\n");
        fprintf(fff,"SIP URI			 	 	LOCATION\n");
        fprintf(fff,"%s 		    (%f,%f) \n",ind.mac,Xmn,Ymn);
        fprintf(fff,"[email protected]  		 	(2.8,8.7) \n");
        fprintf(fff,"[email protected]  		 	(3.5,1.2) \n");
        fprintf(fff,"-----------------------------------------------------------------------------------\n");
        fprintf(fff,"\n");
        fprintf(fff,"\n");	
        fprintf(fff,"******************************************************************************************************************************\n");
        fprintf(fff,"		 	%s 	 	 	[email protected] 	 	 	[email protected]\n",ind.mac);
        fprintf(fff,"%s 	 	X			  	      %f                                %f \n",ind.mac,Distance2,Distance1);
        fprintf(fff,"Sally 	 	 	   %f			                 X                                    %f \n",Distance2,Distance3);
        fprintf(fff,"Kyle 	 	 	   %f			              %f                                   X \n",Distance1,Distance3);
        fprintf(fff,"mimos 	 	 	   %f			              %f                                      %f \n",a,Distance4,Distance5);
        fprintf(fff,"mimos1 	 	 	   %f			              %f                                      %f \n",b,Distance9,Distance8);
        fprintf(fff,"mimos2 	 	 	   %f			              %f                                      %f \n",c,Distance6,Distance7);
        fprintf(fff,"******************************************************************************************************************************\n");	
        fclose(ff);
        fclose(fff);
          }
}
}
else
printf("Please wait ...... \n");                    
} //end if
else
printf("Please wait ...... \n");
} //end for loop
//fclose(f);
} //end infinate for loop	 
}	
}
Esempio n. 13
0
bool xBlog::Run(const char *ip, uint16 port, uint32 timeout_secs, uint32 nthreads)
{
    int ret = -1;
    int skt = BindSocket(ip, port);

    if (skt < 0)
    {
        log_error("BindSocket %s %d error\r\n", ip, port);
        return false;
    }

#ifdef _WIN32

    HANDLE ths[128];

    for (uint32 i = 0; i < nthreads; i++)
    {
        struct event_base *base = event_base_new();
        if (base == NULL)
        {
            return false;
        }

        struct evhttp *httpd = evhttp_new(base);
        if (httpd == NULL)
        {
            return false;
        }

        ret = evhttp_accept_socket(httpd, skt);
        if (ret != 0)
        {
            return false;
        }

        SetRouteTable(httpd);

        ths[i] = CreateThread(NULL, NULL, (LPTHREAD_START_ROUTINE) xBlog::Dispatch, base, NULL, NULL);
        log_info("%d %d \r\n", i, ths[i]);
        if (ret != 0)
        {
            return false;
        }
    }

#else

    pthread_t ths[128];
    for (uint32 i = 0; i < nthreads; i++)
    {
        struct event_base *base = event_base_new();
        if (base == NULL)
        {
            return false;
        }

        struct evhttp *httpd = evhttp_new(base);
        if (httpd == NULL)
        {
            return false;
        }

        ret = evhttp_accept_socket(httpd, skt);
        if (ret != 0)
        {
            return false;
        }

        SetRouteTable(httpd);

        ret = pthread_create(&ths[i], NULL, xBlog::Dispatch, base);
        log_info("%d %d \r\n", i, ths[i]);
        if (ret != 0)
        {
            return false;
        }
            
    }

    /*
       for (int i = 0; i < nthreads; i++)
       { 
       pthread_join(ths[i], NULL); 
       }
     */

#endif

    return true;
}
Esempio n. 14
0
//todo len+sizeof(struct tpacket_hdr) has to be equal with frame
void StartInjector(struct ISlist *iq)
{
    struct ifreq              newfl;
    struct iovec              packet_ring;
	struct tpacket_hdr        *packet_hdr;
	struct pollfd             pfd;
    register int              i;
    struct sockaddr_ll	      sock_ll;
    int                       size;
    int                       data_off, blocknum;
    
    data_off = TPACKET_HDRLEN- sizeof(struct sockaddr_ll);
    //create socket
    iq -> fd = CreateSocket(PF_PACKET, SOCK_RAW, iq -> args -> protocol);
    //get index bind socket
    newfl = GetIndex(iq -> fd, iq ->args->device);
    memset((char *)&sock_ll, '\0', sizeof(struct sockaddr_ll));
    sock_ll.sll_family = AF_PACKET;
    sock_ll.sll_protocol = htons(iq->args->protocol);
    sock_ll.sll_ifindex = newfl.ifr_ifindex;
    BindSocket(iq -> fd, (struct sockaddr *)&sock_ll, 
            sizeof(struct sockaddr_ll));
	  iq -> packet_req = CalculatePacket();
	  RequestPacketRing(iq -> fd, PACKET_TX_RING, *(iq -> packet_req));
      //map shared memory
      size = iq -> packet_req -> tp_block_size * iq -> 
          packet_req -> tp_block_nr;
      iq -> ps_hdr_start =(unsigned char *) mmap(0, size,
            PROT_READ|PROT_WRITE, MAP_SHARED, iq -> fd, 0);
      
      if ( iq -> ps_hdr_start == MAP_FAILED )
      {
          perror("mmap()");
          DestroySocket(iq -> fd);
          exit(ERROR);
      }
      //poll for our fd
      pfd.fd = iq -> fd;
      pfd.revents = 0;
      pfd.events = POLLIN|POLLRDNORM|POLLERR;
      
      i = 0;
      while (i < iq ->args->packet_num || iq->args->packet_num == 0 )
      {
          packet_hdr = (struct tpacket_hdr *)(iq -> ps_hdr_start+iq ->
                packet_req -> tp_frame_size*i);
          
          switch(packet_hdr -> tp_status)
          {
              case TP_STATUS_AVAILABLE:
                  packet_ring.iov_base = ((unsigned char *)packet_hdr+data_off);
                  iq -> args -> FunctionPtr(&packet_ring, iq -> args ->argv);
                  packet_hdr -> tp_len = packet_ring.iov_len;
                  if ( packet_hdr -> tp_len == 0 )
                      break;
                  packet_hdr->tp_status = TP_STATUS_SEND_REQUEST;
                  
                  if ( sendto(iq -> fd, NULL, 0, MSG_DONTWAIT, NULL,
                            0) == ERROR )
                  {
                      perror("send:");
                      exit(ERROR);
                  }
                  if ( iq -> args-> packet_num >= iq -> packet_req -> tp_frame_nr )
                      iq -> args -> packet_num--;
                  i = (((unsigned)i) == (unsigned)iq -> 
                          packet_req -> tp_frame_nr-1)? 0 : i+1;
                  break;
              case TP_STATUS_SENDING:
                  if ( poll(&pfd, 1, -1) < 0 )
                  {
                      perror("poll: ");
                      exit(ERROR);
                  }
                  break;
              case TP_STATUS_WRONG_FORMAT:
                  fprintf(stderr, "An error has occured during"
                        "transfer\n");
                  exit(ERROR);
        }
    }
}
int main( int argc, char *argv[] )
{
	int				iPort;
	int				iSocket;
	
	if( argc != 2 ) {
		printf( "Usage:  demoserver <port #>\n" );
		return 1;
	}
	
	if( geteuid() != 0 ) {
		printf( "Warning:  Tool must be run as EUID = 0 to use Kerberos/GSSAPI\n" );
	}
	
	// if we were relying on Kerberos for this service, we could pre-flight our 
	// service principal before we start the service, or just let GSSAPI determine 
	// at the time of connection
	//
	// we have opted for at time of connection, because we don't know what we
	// are using uses for service principal

	// let's convert the string provided for the port into a number
	iPort = strtol( argv[1], NULL, 10 );
	
	// don't allow privileged ports for this test
	if( iPort < 1024 ) {
		printf( "Error:  Port value must be greater than 1024\n" );
	}
	
	// this demonstration code will wait for an authentication identification code
	//    GSSAPI
	//    CRAM-MD5
	//    cleartext
	// Once method is determined, it will attempt to authenticate the user
	
	iSocket = BindSocket( iPort );
	if( iSocket > 0 ) {
		
		// just informative
		printf( "Listening on port %d\n", iPort );

		// go into a loop until we are killed
		while( 1 ) {

			int	iAccept;
			
			// Accept a TCP connection
			if( (iAccept = accept(iSocket, NULL, 0)) < 0) {
				printf("Error:  Couldn't accept connection");
				continue;
			}
			
			// once we have a connection, go to our request-response loop
			if( HandleNewConnection( iAccept ) == 0 ) {
				
				// if we had no error we could go do something, but in this case we will
				// just close the connection

				close( iAccept );
				iAccept = 0;
				
			} else {

				// close our socket
				close( iAccept );
				iAccept = 0;
			}
		}
		
		// close our socket
		close( iSocket );
		iSocket = 0;

	} else {
		printf( "Error:  Unable to listen on port %d\n", iPort );
		return 1;
	}

	return 0;
}