/*****************************************************************************
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);
}
/**
* 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);
//.........这里部分代码省略.........
/*
* 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++;
}
//.........这里部分代码省略.........
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
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,
//.........这里部分代码省略.........
请发表评论