首页 > 其他分享 >soket 利用http实现验证码的发送

soket 利用http实现验证码的发送

时间:2024-06-07 22:34:29浏览次数:18  
标签:http socket soket 验证码 sin HTTP include servaddr

soket 利用http实现验证码的发送

在C语言中,可以直接使用socket的TCP连接来实现HTTP协议发送验证码的功能会涉及到底层的网络通信编程。以下是一个简化的步骤和示例代码,如何使用socket在程序中向互亿无线官方中发送HTTP POST请求来让手机获取验证码。

详情可以去官网下载API文档了解

互亿无线

程序步骤

  1. 创建socket:首先,你需要创建一个socket描述符,用于网络通信。
  2. 连接到服务器:使用connect函数连接到验证码服务器的IP地址和端口(通常是80或443,如果是HTTPS)。
  3. 构建HTTP请求:构建一个包含所有必要参数的HTTP POST请求。这通常包括请求行、请求头和请求体。
  4. 发送HTTP请求:通过socket发送HTTP请求到服务器。
  5. 接收并处理响应:接收服务器的HTTP响应,并解析它以检查验证码是否已发送。
  6. 关闭socket:在完成通信后,关闭socket描述符。

程序示例

/*******************************************************************
*
*	file name:	sms.c
*	author	 :  [email protected]
*	date	 :  2024/06/07
*	function :  利用http连接互亿无线官方API接口,实现4位数的验证码短信随机生成发送
*				
* 	note	 :  None
*
*	CopyRight (c)  2023-2024   [email protected]  All Right Reseverd 
*
* *****************************************************************/
#include <stdio.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <time.h>
#include <errno.h>
#include <signal.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/time.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>

#define host "106.ihuyi.com"
#define PORT 80
#define BUFSIZE 4096
#define APIID   "xxxxxxx" //以下三参数替换为自己的参数信息
#define APIKEY  "xxxxxxxxxxxxxxx"
#define PHONE   "xxxxxxxxxxxx"

int vercode;
int main(int argc, char **argv)
{
    int sockfd, ret, i, h,srandnum;
    struct sockaddr_in servaddr;
    char str1[4096], str2[4096], buf[BUFSIZE], *str;
    socklen_t len;
    fd_set t_set1;
    struct timeval tv;

    if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0 ) { //创建套接字
        printf("create connect error!\n"); //创建网络连接失败
        exit(0);
    };

    bzero(&servaddr, sizeof(servaddr)); //每个字节都用0填充
    servaddr.sin_family = AF_INET; //使用IPv4地址
    servaddr.sin_port = htons(PORT); //端口

    if (inet_aton(host, &servaddr.sin_addr) == 0){
        struct hostent *he;
        he = gethostbyname(host);
        if (he == NULL)
            return -1;
        memcpy(&servaddr.sin_addr, he->h_addr, sizeof(struct in_addr));
    }
    char ipbuf[128];
    strncpy(ipbuf, inet_ntoa(servaddr.sin_addr), 128); //将域名转成IP

    if (inet_pton(AF_INET, ipbuf, &servaddr.sin_addr) <= 0 ){
            printf("inet_pton error!\n"); //创建网络连接失败
            exit(0);
    };

    if (connect(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr)) < 0){
            printf("connect error!\n");
            exit(0);
    }
    printf("connect success!\n\n");

     srand(time(NULL));
     vercode=rand()%9999;

    //发送数据
    sprintf(str1, "POST /webservice/sms.php?method=Submit&format=json HTTP/1.1\r\n"
                "Host: 106.ihuyi.com\r\n"
                "Content-Type: application/x-www-form-urlencoded\r\n"
                "Content-Length: 212\r\n"
                "\r\n"
                "account=%s&password=%s&mobile=%s&content=您的充电桩注册验证码是:%d。请在5分钟内使用,切勿泄露给他人。如非本人操作,请忽略。",
                APIID,APIKEY,PHONE,vercode);
    printf("Request Data: \n%s\n",str1);

    ret = write(sockfd,str1,strlen(str1));
    if (ret < 0) {
        printf("send data fail!errno:%d, errmsg:'%s'\n\n",errno, strerror(errno));
        exit(0);
    }else{
        printf("send data success, length:%d byte!\n\n", ret);
    }

    FD_ZERO(&t_set1);
    FD_SET(sockfd, &t_set1);

    while(1){
        //sleep(1);
        tv.tv_sec= 0;
        tv.tv_usec= 0;
        h = select(sockfd+1, &t_set1, NULL, NULL, &tv);
        printf("h:%d sec:%ld usec:%ld\n\n", h, tv.tv_sec, tv.tv_usec);

        if (h == 0) {
            memset(buf, 0, 4096);
            i= read(sockfd, buf, 4095);
            if (i==0){
                close(sockfd);//关闭套接字
                printf("0.connect close!\n"); //读取数据报文时发现远端关闭
                return -1;
            }
            printf("Response Data: \n%s\n", buf);
            close(sockfd);//关闭套接字
            printf("1.connect close!\n");
            return 1;
        }

        if (h > 0) {
            close(sockfd);//关闭套接字
            printf("2.connect close!\n");
            return -1;
        };

        if (h < 0) {
            close(sockfd);//关闭套接字
            printf("3.connect close!\n"); //在读取数据报文时SELECT检测到异常
            return -1;
        };

        //continue;
        //break;
    }
    close(sockfd);//关闭套接字
    printf("4.connect close!\n");

    return 0;
}

运行以上代码编译运行后,程序会向服务器发送http请求,几秒后手机会收到随机的验证码,当然前提是你已经注册登录过互亿无线的账号。

如果代码用法有什么问题,请将问题发至网易邮箱 [email protected],作者将及时改正,欢迎与各位老爷交流讨论。

麻烦三连加关注!!!!

比心

标签:http,socket,soket,验证码,sin,HTTP,include,servaddr
From: https://www.cnblogs.com/zkbklink/p/18237964

相关文章

  • 解决Docker遇到error NU1301: Unable to load the service index for source https://
    解决Docker容器内无法通过HTTPS访问外部网络的问题在使用Docker构建.NET项目时,有时会遇到无法通过HTTPS访问外部网络的问题,导致dotnetrestore命令无法从NuGet源下载依赖项。本文将介绍一种通过修改Docker配置文件config.json来解决该问题的方法。问题描述在......
  • Serverless 使用阿里云OOS将http文件转存到对象存储
    背景介绍系统运维管理OOS系统运维管理OOS(CloudOpsOrchestrationService)提供了一个高度灵活和强大的解决方案,通过精巧地编排阿里云提供的OpenAPI,使得用户能够将分散的单个原子运维任务链接起来,形成复杂的运维场景和流程。这种方式不仅大幅提升了运维的效率,也极大地减少了人为错......
  • GuzzleHttp 并发发起 http 请求
    GuzzleHttp并发发起http请求‍系统中需要调用百度翻译接口做多语言支持,百度翻译对于不同的认证给予了不同的权益,通用文本翻译API标准版、高级版、尊享版的不同服务权益如下:标准版高级版尊享版QPS=1支持28个语种互译单次最长请求1000字符免费调用量5万字符/月QPS=......
  • Maui+blazor中使用https时信任所有证书
    Maui中的Android使用https时信任所有证书前言最近使用Maui+blazor写了一个Androidapp,需要调用webapi接口,同时需要用websock与服务器通信,在使用http和https中遇到一些问题httpAndroid默认禁止http,想要使用http需要在Platforms\Android目录下找到AndroidManifest.xml文件,然后......
  • Http协议详解之三次握手
    HTTP的三次握手在计算机网络中,HTTP(HyperTextTransferProtocol,超文本传输协议)是用于在客户端和服务器之间传输超文本的协议。尽管HTTP本身是一个无状态的应用层协议,但它通常依赖于TCP(TransmissionControlProtocol,传输控制协议)来确保数据的可靠传输。TCP是一种面向连接的......
  • HTTP Status 400 – Bad Request
    1.问题2.原因org.apache.juli.logging.DirectJDKLog:log|ErrorparsingHTTPrequestheaderNote:furtheroccurrencesofHTTPheaderparsingerrorswillbeloggedatDEBUGlevel.java.lang.IllegalArgumentException:Requestheaderistoolargeat......
  • 调用文心一言API询问httpx的使用方法2
    [importrequestsimportjsondefget_access_token():url="https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=输入自己的id&client_secret=输入自己id的密码"payload=json.dumps("")headers={"Content-Typ......
  • Spark读取http数据写入hive
    http请求hutool,json转换数据写入到rdd,之后转换为sparksqlSparkSessionspark=SparkSession.builder().master("yarn").appName("json2hive").config("hive.exec.dynamic.partition","true").config("......
  • 调用文心一言API询问httpx的使用方法
    importrequestsimportjsondefget_access_token():url="https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=输入自己的id&client_secret=输入自己id的密码"payload=json.dumps("")headers={"Content-Type......
  • Vue简单自定义Canvas验证码组件。
    在您的Vue项目中,是否曾遇到过需要增加验证码来增强账户安全性的情况?这个Vue通用Canvas验证码组件!采用Canvas,实现了高度自定义和灵活的验证码生成方式,让您的网站或应用轻松应对各类验证码需求。在线演示地址:原文可查看演示一,创建一个Captcha验证码组件。<template><can......