目录
mysql通信报文结构
初始握手包
生成初始握手包
首页 数据库 mysql教程 详细介绍mysql 协议的服务端握手包及对其解析

详细介绍mysql 协议的服务端握手包及对其解析

May 12, 2018 pm 04:41 PM

概况

mysql客户端登陆到mysql服务端需要一个交互的过程,这里先看服务端给客户端发送的初始握手包。如下,client通过socket连接到server指定的端口后,server将往client发送初始握手包。服务端会根据不同的服务版本和不同的配置返回不同的初始化握手包。

client              
server   
|------connect---- >|
   |                   |
   |<----handshake-----|
   |                   |
   |                   |
   |                   |
登录后复制

mysql通信报文结构

类型名字描述
int<3>payload长度按照the least significant byte first存储,3个字节的payload和1个字节的序列号组合成报文头
int<1>序列号
stringpayload报文体,长度即为前面指定的payload长度

初始握手包

HandshakeV10协议如下

1              [0a] protocol version
string[NUL]    server version
4              connection id
string[8]      auth-plugin-data-part-1
1              [00] filler
2              capability flags (lower 2 bytes)
  if more data in the packet:
1              character set
2              status flags
2              capability flags (upper 2 bytes)
  if capabilities & CLIENT_PLUGIN_AUTH {
1              length of auth-plugin-data
  } else {
1              [00]
  }
string[10]     reserved (all [00])
  if capabilities & CLIENT_SECURE_CONNECTION {
string[$len]   auth-plugin-data-part-2 ($len=MAX(13, length of auth-plugin-data - 8))
  if capabilities & CLIENT_PLUGIN_AUTH {
    if version >= (5.5.7 and < 5.5.10) or (>= 5.6.0 and < 5.6.2) {
string[EOF]    auth-plugin name
    } elseif version >= 5.5.10 or >= 5.6.2 {
string[NUL]    auth-plugin name
    }
  }
登录后复制

生成初始握手包

  1. 定义版

/**
 * 
 * @author seaboat
 * @date 2016-09-25
 * @version 1.0
 * <pre class="brush:php;toolbar:false"><b>email: </b>849586227@qq.com
*
<b>blog: </b>http://www.php.cn/;/pre>
 * <p>proxy&#39;s version.</p>
 */public interface Versions {

    byte PROTOCOL_VERSION = 10;    byte[] SERVER_VERSION = "5.6.0-snapshot".getBytes();
}
登录后复制
  1. 随机数工具

/**
 * 
 * @author seaboat
 * @date 2016-09-25
 * @version 1.0
 * <pre class="brush:php;toolbar:false"><b>email: </b>849586227@qq.com
*
<b>blog: </b>http://www.php.cn/;/pre>
 * <p>a random util .</p>
 */public class RandomUtil {
    private static final byte[] bytes = { &#39;1&#39;, &#39;2&#39;, &#39;3&#39;, &#39;4&#39;, &#39;5&#39;, &#39;6&#39;, &#39;7&#39;,            
    &#39;8&#39;, &#39;9&#39;, &#39;0&#39;, &#39;q&#39;, &#39;w&#39;, &#39;e&#39;, &#39;r&#39;, &#39;t&#39;, &#39;y&#39;, &#39;u&#39;, &#39;i&#39;, &#39;o&#39;, &#39;p&#39;,            
    &#39;a&#39;, &#39;s&#39;, &#39;d&#39;, &#39;f&#39;, &#39;g&#39;, &#39;h&#39;, &#39;j&#39;, &#39;k&#39;, &#39;l&#39;, &#39;z&#39;, &#39;x&#39;, &#39;c&#39;, &#39;v&#39;,            
    &#39;b&#39;, &#39;n&#39;, &#39;m&#39;, &#39;Q&#39;, &#39;W&#39;, &#39;E&#39;, &#39;R&#39;, &#39;T&#39;, &#39;Y&#39;, &#39;U&#39;, &#39;I&#39;, &#39;O&#39;, &#39;P&#39;,            
    &#39;A&#39;, &#39;S&#39;, &#39;D&#39;, &#39;F&#39;, &#39;G&#39;, &#39;H&#39;, &#39;J&#39;, &#39;K&#39;, &#39;L&#39;, &#39;Z&#39;, &#39;X&#39;, &#39;C&#39;, &#39;V&#39;,            
    &#39;B&#39;, &#39;N&#39;, &#39;M&#39; };    
    private static final long multiplier = 0x5DEECE66DL;    
    private static final long addend = 0xBL;    
    private static final long mask = (1L << 48) - 1;    
    private static final long integerMask = (1L << 33) - 1;    
    private static final long seedUniquifier = 8682522807148012L;    
    private static long seed;    
    static {        
    long s = seedUniquifier + System.nanoTime();
        s = (s ^ multiplier) & mask;
        seed = s;
    }    public static final byte[] randomBytes(int size) {        
    byte[] bb = bytes;        
    byte[] ab = new byte[size];        
    for (int i = 0; i < size; i++) {
            ab[i] = randomByte(bb);
        }        return ab;
    }    private static byte randomByte(byte[] b) {        
    int ran = (int) ((next() & integerMask) >>> 16);        
    return b[ran % b.length];
    }    private static long next() {        
    long oldSeed = seed;        
    long nextSeed = 0L;
        do {
            nextSeed = (oldSeed * multiplier + addend) & mask;
        } 
        while (oldSeed == nextSeed);
        seed = nextSeed;        
        return nextSeed;
    }

}
登录后复制
  1. mysql包基类

/**
 * 
 * @author seaboat
 * @date 2016-09-25
 * @version 1.0
 * <pre class="brush:php;toolbar:false"><b>email: </b>849586227@qq.com
*
<b>blog: </b>http://www.php.cn/;/pre>
 * <p>MySQLPacket is mysql&#39;s basic packet.</p>
 */public abstract class MySQLPacket {
    /**
     * none, this is an internal thread state
     */
    public static final byte COM_SLEEP = 0;    /**
     * mysql_close
     */
    public static final byte COM_QUIT = 1;    /**
     * mysql_select_db
     */
    public static final byte COM_INIT_DB = 2;    /**
     * mysql_real_query
     */
    public static final byte COM_QUERY = 3;    /**
     * mysql_list_fields
     */
    public static final byte COM_FIELD_LIST = 4;    /**
     * mysql_create_db (deprecated)
     */
    public static final byte COM_CREATE_DB = 5;    /**
     * mysql_drop_db (deprecated)
     */
    public static final byte COM_DROP_DB = 6;    /**
     * mysql_refresh
     */
    public static final byte COM_REFRESH = 7;    /**
     * mysql_shutdown
     */
    public static final byte COM_SHUTDOWN = 8;    /**
     * mysql_stat
     */
    public static final byte COM_STATISTICS = 9;    /**
     * mysql_list_processes
     */
    public static final byte COM_PROCESS_INFO = 10;    /**
     * none, this is an internal thread state
     */
    public static final byte COM_CONNECT = 11;    /**
     * mysql_kill
     */
    public static final byte COM_PROCESS_KILL = 12;    /**
     * mysql_dump_debug_info
     */
    public static final byte COM_DEBUG = 13;    /**
     * mysql_ping
     */
    public static final byte COM_PING = 14;    /**
     * none, this is an internal thread state
     */
    public static final byte COM_TIME = 15;    /**
     * none, this is an internal thread state
     */
    public static final byte COM_DELAYED_INSERT = 16;    /**
     * mysql_change_user
     */
    public static final byte COM_CHANGE_USER = 17;    /**
     * used by slave server mysqlbinlog
     */
    public static final byte COM_BINLOG_DUMP = 18;    /**
     * used by slave server to get master table
     */
    public static final byte COM_TABLE_DUMP = 19;    /**
     * used by slave to log connection to master
     */
    public static final byte COM_CONNECT_OUT = 20;    /**
     * used by slave to register to master
     */
    public static final byte COM_REGISTER_SLAVE = 21;    /**
     * mysql_stmt_prepare
     */
    public static final byte COM_STMT_PREPARE = 22;    /**
     * mysql_stmt_execute
     */
    public static final byte COM_STMT_EXECUTE = 23;    /**
     * mysql_stmt_send_long_data
     */
    public static final byte COM_STMT_SEND_LONG_DATA = 24;    /**
     * mysql_stmt_close
     */
    public static final byte COM_STMT_CLOSE = 25;    /**
     * mysql_stmt_reset
     */
    public static final byte COM_STMT_RESET = 26;    /**
     * mysql_set_server_option
     */
    public static final byte COM_SET_OPTION = 27;    /**
     * mysql_stmt_fetch
     */
    public static final byte COM_STMT_FETCH = 28;    /**
     * mysql packet length
     */
    public int packetLength;    /**
     * mysql packet id
     */
    public byte packetId;    /**
     * calculate mysql packet length
     */
    public abstract int calcPacketSize();    /**
     * mysql packet info
     */
    protected abstract String getPacketInfo();    @Override
    public String toString() {        return new StringBuilder().append(getPacketInfo()).append("{length=")
                .append(packetLength).append(",id=").append(packetId)
                .append(&#39;}&#39;).toString();
    }

}
登录后复制
  1. 握手包类

/**
 * 
 * @author seaboat
 * @date 2016-09-25
 * @version 1.0
 * <pre class="brush:php;toolbar:false"><b>email: </b>849586227@qq.com
*
<b>blog: </b>http://www.php.cn/;/pre>
 * <p>AuthPacket means mysql initial handshake packet .</p>
 */public class HandshakePacket extends MySQLPacket {
    private static final byte[] FILLER_13 = new byte[] { 0, 0, 0, 0, 0, 0, 0,            
    0, 0, 0, 0, 0, 0 };    
    public byte protocolVersion;    
    public byte[] serverVersion;    
    public long threadId;    
    public byte[] seed;    
    public int serverCapabilities;    
    public byte serverCharsetIndex;    
    public int serverStatus;    
    public byte[] restOfScrambleBuff;    
    public void read(byte[] data) {
        MySQLMessage mm = new MySQLMessage(data);
        packetLength = mm.readUB3();
        packetId = mm.read();
        protocolVersion = mm.read();
        serverVersion = mm.readBytesWithNull();
        threadId = mm.readUB4();
        seed = mm.readBytesWithNull();
        serverCapabilities = mm.readUB2();
        serverCharsetIndex = mm.read();
        serverStatus = mm.readUB2();
        mm.move(13);
        restOfScrambleBuff = mm.readBytesWithNull();
    }    @Override
    public int calcPacketSize() {        int size = 1;
        size += serverVersion.length;// n
        size += 5;// 1+4
        size += seed.length;// 8
        size += 19;// 1+2+1+2+13
        size += restOfScrambleBuff.length;// 12
        size += 1;// 1
        return size;
    }    public void write(ByteBuffer buffer) {
        BufferUtil.writeUB3(buffer, calcPacketSize());
        buffer.put(packetId);
        buffer.put(protocolVersion);
        BufferUtil.writeWithNull(buffer, serverVersion);
        BufferUtil.writeUB4(buffer, threadId);
        BufferUtil.writeWithNull(buffer, seed);
        BufferUtil.writeUB2(buffer, serverCapabilities);
        buffer.put(serverCharsetIndex);
        BufferUtil.writeUB2(buffer, serverStatus);
        buffer.put(FILLER_13);
        BufferUtil.writeWithNull(buffer, restOfScrambleBuff);
    }    @Override
    protected String getPacketInfo() {        
    return "MySQL Handshake Packet";
    }

}
登录后复制
  1. 服务端能力类

/**
 * 
 * @author seaboat
 * @date 2016-09-25
 * @version 1.0
 * <pre class="brush:php;toolbar:false"><b>email: </b>849586227@qq.com
*
<b>blog: </b>http://www.php.cn/;/pre>
 * <p>server capabilities .</p>
 */public interface Capabilities {

    // new more secure passwords
    int CLIENT_LONG_PASSWORD = 1;    // Found instead of affected rows
    int CLIENT_FOUND_ROWS = 2;    // Get all column flags
    int CLIENT_LONG_FLAG = 4;    // One can specify db on connect
    int CLIENT_CONNECT_WITH_DB = 8;    // Don&#39;t allow database.table.column
    int CLIENT_NO_SCHEMA = 16;    // Can use compression protocol
    int CLIENT_COMPRESS = 32;    // Odbc client
    int CLIENT_ODBC = 64;    // Can use LOAD DATA LOCAL
    int CLIENT_LOCAL_FILES = 128;    // Ignore spaces before &#39;(&#39;
    int CLIENT_IGNORE_SPACE = 256;    // New 4.1 protocol This is an interactive client
    int CLIENT_PROTOCOL_41 = 512;    // This is an interactive client
    int CLIENT_INTERACTIVE = 1024;    // Switch to SSL after handshake
    int CLIENT_SSL = 2048;    // IGNORE sigpipes
    int CLIENT_IGNORE_SIGPIPE = 4096;    // Client knows about transactions
    int CLIENT_TRANSACTIONS = 8192;    // Old flag for 4.1 protocol
    int CLIENT_RESERVED = 16384;    // New 4.1 authentication
    int CLIENT_SECURE_CONNECTION = 32768;    // Enable/disable multi-stmt support
    int CLIENT_MULTI_STATEMENTS = 65536;    // Enable/disable multi-results
    int CLIENT_MULTI_RESULTS = 131072;

}
登录后复制
  1. 测试类

/**
 * 
 * @author seaboat
 * @date 2016-09-25
 * @version 1.0
 * <pre class="brush:php;toolbar:false"><b>email: </b>849586227@qq.com
*
<b>blog: </b>http://www.php.cn/;/pre>
 * <p>test handshake packet.</p>
 */public class HandshakePacketTest {
    private final static byte[] hex = "0123456789ABCDEF".getBytes();    @Test
    public void produce() {        
    byte[] rand1 = RandomUtil.randomBytes(8);        
    byte[] rand2 = RandomUtil.randomBytes(12);        
    byte[] seed = new byte[rand1.length + rand2.length];
        System.arraycopy(rand1, 0, seed, 0, rand1.length);
        System.arraycopy(rand2, 0, seed, rand1.length, rand2.length);
        HandshakePacket hs = new HandshakePacket();
        hs.packetId = 0;
        hs.protocolVersion = Versions.PROTOCOL_VERSION;
        hs.serverVersion = Versions.SERVER_VERSION;
        hs.threadId = 1000;
        hs.seed = rand1;
        hs.serverCapabilities = getServerCapabilities();
        hs.serverCharsetIndex = (byte) (CharsetUtil.getIndex("utf8") & 0xff);
        hs.serverStatus = 2;
        hs.restOfScrambleBuff = rand2;

        ByteBuffer buffer = ByteBuffer.allocate(256);
        hs.write(buffer);
        buffer.flip();        
        byte[] bytes = new byte[buffer.remaining()];
        buffer.get(bytes, 0, bytes.length);
        String result = Bytes2HexString(bytes);
        assertTrue(Integer.valueOf(result.substring(0,2),16)==result.length()/2-4);
    }    public static String Bytes2HexString(byte[] b) {        
    byte[] buff = new byte[2 * b.length];        
    for (int i = 0; i < b.length; i++) {
            buff[2 * i] = hex[(b[i] >> 4) & 0x0f];
            buff[2 * i + 1] = hex[b[i] & 0x0f];
        }        return new String(buff);
    }    public static String str2HexStr(String str) {        
    char[] chars = "0123456789ABCDEF".toCharArray();
        StringBuilder sb = new StringBuilder("");        
        byte[] bs = str.getBytes();        
        int bit;        
        for (int i = 0; i < bs.length; i++) {
            bit = (bs[i] & 0x0f0) >> 4;
            sb.append(chars[bit]);
            bit = bs[i] & 0x0f;
            sb.append(chars[bit]);
        }        return sb.toString();
    }    protected int getServerCapabilities() {        
    int flag = 0;
        flag |= Capabilities.CLIENT_LONG_PASSWORD;
        flag |= Capabilities.CLIENT_FOUND_ROWS;
        flag |= Capabilities.CLIENT_LONG_FLAG;
        flag |= Capabilities.CLIENT_CONNECT_WITH_DB;
        flag |= Capabilities.CLIENT_ODBC;
        flag |= Capabilities.CLIENT_IGNORE_SPACE;
        flag |= Capabilities.CLIENT_PROTOCOL_41;
        flag |= Capabilities.CLIENT_INTERACTIVE;
        flag |= Capabilities.CLIENT_IGNORE_SIGPIPE;
        flag |= Capabilities.CLIENT_TRANSACTIONS;
        flag |= Capabilities.CLIENT_SECURE_CONNECTION;        
        return flag;
    }

}
登录后复制


以上是详细介绍mysql 协议的服务端握手包及对其解析的详细内容。更多信息请关注PHP中文网其他相关文章!

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

AI Hentai Generator

AI Hentai Generator

免费生成ai无尽的。

热门文章

R.E.P.O.能量晶体解释及其做什么(黄色晶体)
3 周前 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳图形设置
3 周前 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您听不到任何人,如何修复音频
3 周前 By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25:如何解锁Myrise中的所有内容
3 周前 By 尊渡假赌尊渡假赌尊渡假赌

热工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

mysql用户和数据库的关系 mysql用户和数据库的关系 Apr 08, 2025 pm 07:15 PM

MySQL 数据库中,用户和数据库的关系通过权限和表定义。用户拥有用户名和密码,用于访问数据库。权限通过 GRANT 命令授予,而表由 CREATE TABLE 命令创建。要建立用户和数据库之间的关系,需创建数据库、创建用户,然后授予权限。

RDS MySQL 与 Redshift 零 ETL 集成 RDS MySQL 与 Redshift 零 ETL 集成 Apr 08, 2025 pm 07:06 PM

数据集成简化:AmazonRDSMySQL与Redshift的零ETL集成高效的数据集成是数据驱动型组织的核心。传统的ETL(提取、转换、加载)流程复杂且耗时,尤其是在将数据库(例如AmazonRDSMySQL)与数据仓库(例如Redshift)集成时。然而,AWS提供的零ETL集成方案彻底改变了这一现状,为从RDSMySQL到Redshift的数据迁移提供了简化、近乎实时的解决方案。本文将深入探讨RDSMySQL零ETL与Redshift集成,阐述其工作原理以及为数据工程师和开发者带来的优势。

mysql 是否要付费 mysql 是否要付费 Apr 08, 2025 pm 05:36 PM

MySQL 有免费的社区版和收费的企业版。社区版可免费使用和修改,但支持有限,适合稳定性要求不高、技术能力强的应用。企业版提供全面商业支持,适合需要稳定可靠、高性能数据库且愿意为支持买单的应用。选择版本时考虑的因素包括应用关键性、预算和技术技能。没有完美的选项,只有最合适的方案,需根据具体情况谨慎选择。

如何针对高负载应用程序优化 MySQL 性能? 如何针对高负载应用程序优化 MySQL 性能? Apr 08, 2025 pm 06:03 PM

MySQL数据库性能优化指南在资源密集型应用中,MySQL数据库扮演着至关重要的角色,负责管理海量事务。然而,随着应用规模的扩大,数据库性能瓶颈往往成为制约因素。本文将探讨一系列行之有效的MySQL性能优化策略,确保您的应用在高负载下依然保持高效响应。我们将结合实际案例,深入讲解索引、查询优化、数据库设计以及缓存等关键技术。1.数据库架构设计优化合理的数据库架构是MySQL性能优化的基石。以下是一些核心原则:选择合适的数据类型选择最小的、符合需求的数据类型,既能节省存储空间,又能提升数据处理速度

mysql用户名和密码怎么填 mysql用户名和密码怎么填 Apr 08, 2025 pm 07:09 PM

要填写 MySQL 用户名和密码,请:1. 确定用户名和密码;2. 连接到数据库;3. 使用用户名和密码执行查询和命令。

MySQL 中的查询优化对于提高数据库性能至关重要,尤其是在处理大型数据集时 MySQL 中的查询优化对于提高数据库性能至关重要,尤其是在处理大型数据集时 Apr 08, 2025 pm 07:12 PM

1.使用正确的索引索引通过减少扫描的数据量来加速数据检索select*fromemployeeswherelast_name='smith';如果多次查询表的某一列,则为该列创建索引如果您或您的应用根据条件需要来自多个列的数据,则创建复合索引2.避免选择*仅选择那些需要的列,如果您选择所有不需要的列,这只会消耗更多的服务器内存并导致服务器在高负载或频率时间下变慢例如,您的表包含诸如created_at和updated_at以及时间戳之类的列,然后避免选择*,因为它们在正常情况下不需要低效查询se

mysql怎么复制粘贴 mysql怎么复制粘贴 Apr 08, 2025 pm 07:18 PM

MySQL 中的复制粘贴包含以下步骤:选择数据,使用 Ctrl C(Windows)或 Cmd C(Mac)复制;在目标位置右键单击,选择“粘贴”或使用 Ctrl V(Windows)或 Cmd V(Mac);复制的数据将插入到目标位置,或替换现有数据(取决于目标位置是否已存在数据)。

mysql怎么查看 mysql怎么查看 Apr 08, 2025 pm 07:21 PM

通过以下命令查看 MySQL 数据库:连接到服务器:mysql -u 用户名 -p 密码运行 SHOW DATABASES; 命令获取所有现有数据库选择数据库:USE 数据库名;查看表:SHOW TABLES;查看表结构:DESCRIBE 表名;查看数据:SELECT * FROM 表名;

See all articles