在我目前的C项目中,我正在尝试使用实现函数来访问需要用户名/密码的json-rpc接口。使用cURL,我成功地使用此命令执行此操作:
curl --user <username>:<password> --data-binary '<json command>' -H 'content-type: text/plain;' <url>
我现在有这个功能:
const char * send_command(const char * command) {
int sockfd, n;
struct sockaddr_in serv_addr;
struct hostent *server;
char * buffer = malloc(MAXBUFFER);
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
error("ERROR opening socket");
server = gethostbyname(URL);
if (server == NULL) {
fprintf(stderr,"ERROR, no such host\n");
exit(0);
}
bzero((char *) &serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
bcopy((char *)server->h_addr, (char *)&serv_addr.sin_addr.s_addr, server->h_length);
serv_addr.sin_port = htons(PORT);
if (connect(sockfd,(struct sockaddr *) &serv_addr,sizeof(serv_addr)) < 0)
error("ERROR connecting");
bzero(buffer,MAXBUFFER);
const char * result = prepare_statement(command);
strcpy(buffer, result);
n = write(sockfd,buffer,strlen(buffer));
if (n < 0)
error("ERROR writing to socket");
bzero(buffer,MAXBUFFER);
n = read(sockfd,buffer,5*MAXBUFFER);
if (n < 0)
error("ERROR reading from socket");
close(sockfd);
return buffer;
}
如果不需要用户名/密码,此功能可以起作用。我如何修改此函数以允许对json-rpc接口进行身份验证访问?