我是C语言中的套接字初学者,并尝试开发我的第一个应用程序 这是客户端代码的一部分,它给了我一个错误 错误是由下面指示的行引起的。
int sockfd = 0;
char fromServer[MAXSIZE];
char * fromClient;
fromClient=(char*)malloc(MAXSIZE * sizeof(char));
struct sockaddr_in remoteServAddr;
sockfd = Socket(AF_INET,SOCK_DGRAM,0);
}
int n;
printf(">>");
scanf("%s",&fromClient); //the error is on this line
sendto(sockfd,fromClient,MAXSIZE,0,(SA*)remoteServAddr,sizeof(remoteServAddr));
更新: 错误已修复,谢谢
答案 0 :(得分:3)
char * fromClient;
fromClient=(char*)malloc(MAXSIZE * sizeof(char))
/* no need to cast, check the result, and sizeof(char) is always 1 */
...
scanf("%s",&fromClient);
/* scanf expects a pointer and fromClient is already a pointer */
应该是
scanf("%s", fromClient);
无论如何,使用fgets
来防止缓冲区溢出:
char *fromClient, *pos;
fgets(fromClient, MAXSIZE, stdin);
if ((pos = strchr(fromClient, '\n')) != NULL)
*pos = '\0';
编辑(由@egur建议):
在sendto
:
<强> dest_addr:强> 指向包含目标地址的sockaddr结构。地址的长度和格式取决于地址族 套接字。
(SA*)remoteServAddr
应该是
(SA*)&remoteServAddr
(假设SA
是struct sockaddr
)的别名
答案 1 :(得分:1)
scanf("%s",&fromClient);
- &GT;
scanf("%s", fromClient); // fromClient is already a char*