在用C编写的一台计算机上,当我试图将字符发送到另一台带有用Python编写的服务器的计算机时,我会得到错误send: Bad address。但地址还不错。
如果我只是发送一个写好的字符串而不是字符,那么"A string written like this"我可以将它很好地发送到服务器,并看到它没有问题地打印出来。所以,我不认为地址真的有问题。
我还尝试将int转换为字符串。编译cannot convert string to char时出错。我已经尝试过变体,我只能用客户端编译,如下所示。
客户( C)
#include <sys/socket.h>
#include <sys/types.h>
#include <netdb.h>
#include <unistd.h>
#include <iostream>
#include <string>
#include <vector>
#include <cstring>
#include <stdio.h>
#include <stdlib.h>
#define ADDR "192.168.0.112"
#define PORT "12003"
void sendall(int socket, char *bytes, int length)
{
int n = 0, total = 0;
while (total < length) {
n = send(socket, bytes + total, total-length, 0);
if (n == -1) {
perror("send");
exit(1);
}
total += n;
}
}
void thesock(char *ADDRf, char *PORTf, char *RAZZstr)
{
struct addrinfo hints = {0}, *addr = NULL;
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
int status = getaddrinfo(ADDRf, PORTf, &hints, &addr);
if (status != 0) {
std::cerr << "Error message";
exit(1);
}
int sock = -1;
struct addrinfo *p = NULL;
for (p = addr; p != NULL; p = addr->ai_next) {
sock = socket(p->ai_family, p->ai_socktype, p->ai_protocol);
if (sock == -1) {
continue;
}
if (connect(sock, p->ai_addr, p->ai_addrlen) != -1) {
break;
}
close(sock);
}
if (p == NULL) {
fprintf(stderr, "connect(), socket()\n");
exit(1);
}
sendall(sock, RAZZstr, 12);
close(sock);
}
int main()
{
int someInt = 321;
char strss[12];
sprintf(strss, "%d", someInt);
thesock(ADDR, PORT, strss);
return 0;
}以上代码的最后一部分是输入字符或字符串的地方。这是代码的这一部分,您可以将thesock中的thesock替换为strss位置"just like this"中的字符串,并将其发送到用strss编写的另一台计算机上的服务器。不过,在编译时,我确实会收到警告ISO C++ forbids converting a string constant to ‘char*’。
服务器(用Python)
import os
import sys
import socket
s=socket.socket()
host='192.168.0.112'
port=12003
s.bind((host,port))
s.listen(11)
while True:
c, addr=s.accept()
content=c.recv(29).decode('utf-8')
print(content) 这台服务器解码utf-8。我不知道在这里我是否可以选择不同的“解码”。我不认为Python有“chars”。
发布于 2022-02-01 14:54:46
TL;DR:就IP地址而言,这与“地址”无关,但它涉及对本地内存访问的无效访问。
int n = 0, total = 0;
while (total < length) {
n = send(socket, bytes + total, total-length, 0);total - length是一个负数,即在您的情况下是0-12 = -12。send的第三个参数为size_t类型,即无符号整数。因此,负数(-12)被转换为无符号整数,从而产生一个巨大的无符号整数。
这导致send访问远远超出为bytes分配的内存的内存,从而导致EFAULT“坏地址”。
https://stackoverflow.com/questions/70940092
复制相似问题