85 lines
2.5 KiB
C
85 lines
2.5 KiB
C
#include "SocketSample.h"
|
|
#include <stdio.h>
|
|
#include <string.h>
|
|
|
|
// --- 1. xSocketInitEnvironment ---
|
|
int xSocketInitEnvironment(void) {
|
|
#ifdef _WIN32
|
|
WSADATA wsaData;
|
|
if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) {
|
|
return SOCKET_FAIL;
|
|
}
|
|
#endif
|
|
return SOCKET_SUCCESS;
|
|
}
|
|
|
|
// --- 2. xSocketCreateUDP ---
|
|
Socket_t xSocketCreateUDP(void) {
|
|
Socket_t xSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
|
|
return xSocket;
|
|
}
|
|
|
|
// --- 3. xSocketBind ---
|
|
int xSocketBind(Socket_t xSocket, uint16_t usPort) {
|
|
struct sockaddr_in xLocalAddr;
|
|
memset(&xLocalAddr, 0, sizeof(xLocalAddr));
|
|
xLocalAddr.sin_family = AF_INET;
|
|
xLocalAddr.sin_port = htons(usPort);
|
|
xLocalAddr.sin_addr.s_addr = INADDR_ANY; // 监听所有网卡
|
|
|
|
if (bind(xSocket, (struct sockaddr*)&xLocalAddr, sizeof(xLocalAddr)) == SOCKET_ERROR_HANDLE) {
|
|
return SOCKET_FAIL;
|
|
}
|
|
return SOCKET_SUCCESS;
|
|
}
|
|
|
|
// --- 4. vSocketClose ---
|
|
void vSocketClose(Socket_t xSocket) {
|
|
if (xSocket == INVALID_SOCKET_HANDLE) return;
|
|
#ifdef _WIN32
|
|
closesocket(xSocket);
|
|
#else
|
|
close(xSocket);
|
|
#endif
|
|
}
|
|
|
|
// --- 5. xSocketSendTo ---
|
|
int32_t xSocketSendTo(Socket_t xSocket, const void* pvBuffer, uint32_t ulLength,
|
|
const char* pcIPAddress, uint16_t usPort) {
|
|
struct sockaddr_in xDestAddr;
|
|
memset(&xDestAddr, 0, sizeof(xDestAddr));
|
|
xDestAddr.sin_family = AF_INET;
|
|
xDestAddr.sin_port = htons(usPort);
|
|
xDestAddr.sin_addr.s_addr = inet_addr(pcIPAddress);
|
|
|
|
int res = sendto(xSocket, (const char*)pvBuffer, (int)ulLength, 0,
|
|
(struct sockaddr*)&xDestAddr, sizeof(xDestAddr));
|
|
|
|
if (res == SOCKET_ERROR_HANDLE) return SOCKET_FAIL;
|
|
return (int32_t)res;
|
|
}
|
|
|
|
// --- 6. xSocketReceiveFrom ---
|
|
int32_t xSocketReceiveFrom(Socket_t xSocket, void* pvBuffer, uint32_t ulLength,
|
|
char* pcIPAddress, uint16_t* pusPort) {
|
|
struct sockaddr_in xSourceAddr;
|
|
#ifdef _WIN32
|
|
int xAddrLen = sizeof(xSourceAddr);
|
|
#else
|
|
socklen_t xAddrLen = sizeof(xSourceAddr);
|
|
#endif
|
|
|
|
int res = recvfrom(xSocket, (char*)pvBuffer, (int)ulLength, 0,
|
|
(struct sockaddr*)&xSourceAddr, &xAddrLen);
|
|
|
|
if (res != SOCKET_ERROR_HANDLE) {
|
|
if (pcIPAddress) {
|
|
char* ip = inet_ntoa(xSourceAddr.sin_addr);
|
|
if (ip) strcpy(pcIPAddress, ip);
|
|
}
|
|
if (pusPort) *pusPort = ntohs(xSourceAddr.sin_port);
|
|
} else {
|
|
return SOCKET_FAIL;
|
|
}
|
|
return (int32_t)res;
|
|
} |