Forum Discussion
2258432
Occasional Contributor
2 years agoI use the functions defined below to send data.
sendData(data, 0x189C000 "192.168.137.1", 12345);
#ifndef ETHERNET_SENDER_H #define ETHERNET_SENDER_H #include <stdio.h> #include <stdlib.h> #include <string.h> #include <arpa/inet.h> #include <sys/socket.h> #include <fcntl.h> #include <unistd.h> void sendData(const uint8_t* data, int size, const char* destIP, int destPort) { struct sockaddr_in serverAddr; int sockfd; sockfd = socket(AF_INET, SOCK_DGRAM, 0); if (sockfd < 0) { perror("socket"); return; } int flags = fcntl(sockfd, F_GETFL, 0); if (flags < 0) { perror("fcntl"); close(sockfd); return; } if (fcntl(sockfd, F_SETFL, flags | O_NONBLOCK) < 0) { perror("fcntl"); close(sockfd); return; } // set server address memset(&serverAddr, 0, sizeof(serverAddr)); serverAddr.sin_family = AF_INET; serverAddr.sin_port = htons(destPort); serverAddr.sin_addr.s_addr = inet_addr(destIP); // Send the data in groups int blockSize = 1450; int numBlocks = (size + blockSize - 1) / blockSize; int totalSent = 0; for (int i = 0; i < numBlocks; i++) { int offset = i * blockSize; int blockBytes = (i == numBlocks - 1) ? (size - offset) : blockSize; ssize_t sentBytes = sendto(sockfd, data+offset, blockBytes, 0, (struct sockaddr*)&serverAddr, sizeof(serverAddr)); totalSent += sentBytes; } close(sockfd); } #endif // ETHERNET_SENDER_H