Sure! Here's an example of how you can create a UDP socket in C using Visual Studio:
#include <winsock2.h> #include <ws2tcpip.h> #pragma comment(lib, "ws2_32.lib") int main() { // Initialize Winsock WSADATA wsaData; int iResult = WSAStartup(MAKEWORD(2, 2), &wsaData); if (iResult != 0) { printf("WSAStartup failed with error: %d\n", iResult); return 1; } // Create a socket SOCKET sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); if (sock == INVALID_SOCKET) { printf("socket failed with error: %ld\n", WSAGetLastError()); WSACleanup(); return 1; } // Set up the sockaddr_in structure SOCKADDR_IN sin; sin.sin_family = AF_INET; sin.sin_port = htons(27015); sin.sin_addr.S_un.S_addr = inet_addr("127.0.0.1"); // Bind the socket to the local IP address and port if (bind(sock, (SOCKADDR*)&sin, sizeof(sin)) == SOCKET_ERROR) { printf("bind failed with error: %ld\n", WSAGetLastError()); closesocket(sock); WSACleanup(); return 1; } // Send a message to the server char sendbuf[1024] = "This is a test message."; int sendlen = strlen(sendbuf) + 1; iResult = sendto(sock, sendbuf, sendlen, 0, (SOCKADDR*)&sin, sizeof(sin)); if (iResult == SOCKET_ERROR) { printf("sendto failed with error: %d\n", WSAGetLastError()); closesocket(sock); WSACleanup(); return 1; } // Receive a message from the server char recvbuf[1024]; int recvlen = sizeof(recvbuf); SOCKADDR_IN from; int fromlen = sizeof(from); iResult = recvfrom(sock, recvbuf, recvlen, 0, (SOCKADDR*)&from, &fromlen); if (iResult == SOCKET_ERROR) { printf("recvfrom failed with error: %d\n", WSAGetLastError()); } else { printf("Received message: %s\n", recvbuf); } // Clean up closesocket(sock); WSACleanup(); return 0;
}
This code creates a UDP socket, binds it to the local IP address and port 27015, and then sends and receives a message to and from itself.




0 comments:
Post a Comment