代碼如下:
int main() {
struct sockaddr_in addr, fromAddr;
int socketd, linkSocketd, num;
size_t size;
char readData[1024] = {'\0'};
addr.sin_family = AF_INET;
addr.sin_port = htons(9900);
addr.sin_addr.s_addr = INADDR_ANY;
socketd = socket(PF_INET, SOCK_STREAM, 0);
if(socketd == -1) {
perror("socket");
return 1;
}
if(bind(socketd, (struct sockaddr*)&addr, 16) == -1) {
perror("bind");
return 1;
}
listen(socketd, 20);
linkSocketd = accept(socketd, (struct sockaddr*)&addr, &size);
if(linkSocketd == -1) {
perror("accept");
return 1;
}
size = sizeof(fromAddr);
readSize = recvfrom(linkSocketd, (void*)&readData, sizeof(readData), 0, &fromAddr, &size);
printf("接收到%d字節\n", readSize);
for(num = 0; num <readSize; num++) {
printf("print_data[%d]:%x\n", num, readData[num]);
}
return 0;
}
結果:
接收到22字節
print_data[0]:68
print_data[1]:3a
print_data[2]:0
print_data[3]:3a
print_data[4]:0
print_data[5]:68
print_data[6]:ffffffc9
print_data[7]:ffffffff
print_data[8]:ffffffff
print_data[9]:1
print_data[10]:69
print_data[11]:0
print_data[12]:2
print_data[13]:73
print_data[14]:0
print_data[15]:0
print_data[16]:1
print_data[17]:0
print_data[18]:0
print_data[19]:0
print_data[20]:ffffffa7
print_data[21]:16
在第6、7、8、20元素的結果為何會出現這種情況?????
char readData[1024] = {'\0'};
修改為
unsigned char readData[1024] = {'\0'};
看看