我目前正在爲學校任務設置一個UDP套接字,但我無法弄清楚如何正確地將sockaddr作爲參數發送到函數中。 SendData的輸入參數的定義方式與sendto函數中的相同。C sockaddr函數調用sendto?
void SendData(int fileDescriptor, const struct sockaddr_in *destAddrUdp, unsigned char buffer[MAXMSG])
{
/* crc */
int strlength = strlen(buffer);
unsigned char SCRC = CRC(buffer, strlength-1);
buffer[strlength-1] = SCRC;
buffer[strlength] = '\0';
/* send */
if (sendto(fileDescriptor, buffer, strlen(buffer), 0, (struct sockaddr*) &destAddrUdp,sizeof(destAddrUdp)) < 0) {
fprintf(stderr, "Could not send data\n");
}
} `
當從main調用下面的代碼時,它會工作,但是當它從SendData調用時,sendto的返回值是-1。
if (sendto(fileDescriptor, buffer, strlen(buffer), 0, (struct sockaddr*) &destAddrUdp,sizeof(destAddrUdp)) < 0) {
fprintf(stderr, "Could not send data\n");
}
如果程序被編譯,我得到警告:傳遞「recvfrom的」的說法,從5不兼容的指針類型。 SendData中的sendto函數調用上的。 在我的主程序的函數調用送出數據是:SendData(sockfd, (struct sockaddr *) &destAddrUdp, buffer);
主程序的情況下,它是相關的:
unsigned char SCRC;
unsigned char strlength;
unsigned char buffer[MAXMSG-5];
unsigned char header[MAXMSG];
struct rtp_struct *sendstruct;
/* option 2 */
struct sockaddr_in destAddrUdp;
int sockfd;
char dstHost[15];
printf("input host IP:\n>");
fgets(dstHost, 15, stdin);
/* Create socket */
if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
fprintf(stderr, "Can't create UDP socket\n");
/* set configurations */
memset (&destAddrUdp, 0, sizeof(destAddrUdp)); //set zero
destAddrUdp.sin_family = AF_INET; //internet use
destAddrUdp.sin_addr.s_addr = inet_addr(dstHost); //set so anyone can connect
destAddrUdp.sin_port = htons(dstUdpPort); //set the port to use
/* Generate CRC table */
GenerateCRCTable();
/* get string and send */
while(1) {
printf("\n>");
fgets(buffer, MAXMSG, stdin);
if(strncmp(buffer,"quit\n",MAXMSG) != 0){ //if read string == quit, see else
strlength = strlen(buffer);
SCRC = CRC(buffer, strlength-1);
buffer[strlength-1] = SCRC;
buffer[strlength] = '\0';
SendData(sockfd, (struct sockaddr *) &destAddrUdp, buffer);
/*if (sendto(sockfd, buffer, strlength, 0, (struct sockaddr *) &destAddrUdp,sizeof(destAddrUdp)) < 0){
fprintf(stderr, "Could not send data\n");}*/
}
else {
close(sockfd);
exit(EXIT_SUCCESS);
}
}
}
快速標準備註:請注意,它是2017年,並且您仍在編寫僅支持傳統IP地址的軟件。最好養成在你的軟件中支持'sockaddr_in6'和'sockaddr_in'(對於傳統IP)的習慣。 (一旦你找出了你當前的問題) – ndim
爲什麼這個'(struct sockaddr *)&destAddrUdp'在'main()'中投射? – alk